有没有一种方法可以“提取”TypeScript接口属性的类型?

1u4esq0p  于 7个月前  发布在  TypeScript
关注(0)|答案(6)|浏览(87)

让我们假设有一个库X的类型文件,其中包括一些接口。

interface I1 {
    x: any;
}
    
interface I2 {
    y: {
        a: I1,
        b: I1,
        c: I1
    }
    z: any
}

字符串
为了使用这个库,我需要传递一个与I2.y类型完全相同的对象。我当然可以在源文件中创建相同的接口:

interface MyInterface {
    a: I1,
    b: I1,
    c: I1
}

let myVar: MyInterface;


但是这样我就有了保持它与图书馆中的那个保持最新的负担,而且它可能非常大,导致大量的代码重复。
因此,有没有办法“提取”接口的这个特定属性的类型?类似于let myVar: typeof I2.y的东西(它不起作用,并导致“找不到名称I2”错误)。

编辑:在TS Playground玩了一段时间后,我注意到下面的代码完全实现了我想要的:

declare var x: I2;
let y: typeof x.y;


然而,它需要声明一个冗余变量x。我正在寻找一种方法来实现这一点没有声明。

utugiqy6

utugiqy61#

这在以前是不可能的,但幸运的是,自从TypeScript version 2.1以来,现在已经可以了。它于2016年12月7日发布,并引入了索引访问类型,也称为查找类型
语法看起来像元素访问,但写在类型的地方。所以在你的例子中:

interface I1 {
    x: any;
}

interface I2 {
    y: {
        a: I1,
        b: I1,
        c: I1
    }
    z: any
}

let myVar: I2['y'];  // indexed access type

字符串
myVar的类型为I2.y
在TypeScript Playground中查看。

shyt4zoc

shyt4zoc2#

要扩展已接受的答案,您还可以使用type关键字分配类型并在其他地方使用它。

// Some obscure library
interface A {
  prop: {
    name: string;
    age: number;
  }
}

// Your helper type
type A_Prop = A['prop']

// Usage
const myThing: A_prop = { name: 'June', age: 29 };

字符串

ergxz8rk

ergxz8rk3#

这是一个从union对象类型中提取文字类型的例子:

type Config = {
    key: "start_time",
    value: number,
} | {
    key: "currency",
    value: string,
}

export type ConfigKey = Config["key"];
// "start_time"|"currency"

字符串

8xiog9wr

8xiog9wr4#

keyof Colors将返回所有键"white" | "black"的列表。当这个键列表被传递到Colors接口时,类型将是给定键"#fff" | #000的所有值。

interface Colors {
  white: "#fff"
  black: "#000"
}

type ColorValues = Colors[keyof Colors]
// ColorValues = "#fff" | "#000"

字符串

c90pui9n

c90pui9n5#

const foo = ()=>{
   return {name: "test", age: 5}
}
type T1 = ReturnType<typeof foo> // {name: string, age: number}
type T2 = ReturnType<typeof foo>['name'] // string
type T3 = T1['age'] // number

字符串

vngu2lb8

vngu2lb86#

一个接口就像一个对象的定义。那么y是你的I2对象的一个属性,它是一个特定的类型,在这种情况下是“匿名”的。
你可以用另一个接口来定义y,然后像这样把它作为y类型

interface ytype {
   a: I1;
   b: I1;
   c: I1;
}

interface I2 {
    y: ytype;
    z: any;
}

字符串
你可以把你的接口放在一个文件中,然后使用extract,这样你就可以把它导入到你项目的其他文件中

export interface ytype {
   a: I1;
   b: I1;
   c: I1;
}


 export interface I2 {
        y: ytype;
        z: any;
    }


你可以这样导入:

import {I1, I2, ytype} from 'your_file'

相关问题