代码之家  ›  专栏  ›  技术社区  ›  artooras

TypeScript从对象接口推断特定的属性类型

  •  0
  • artooras  · 技术社区  · 5 年前

    假设库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游乐场玩了一会儿后,我注意到以下代码完全实现了我想要的:

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

    但是,它需要一个冗余变量 x 待申报。我正在寻找一种在没有这一宣言的情况下实现这一目标的方法。

    0 回复  |  直到 4 年前
        1
  •  409
  •   Michał Miszczyszyn    9 年前

    这在以前是不可能的,但幸运的是现在是了,因为 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 .

        2
  •  13
  •   Ben Winding    5 年前

    要扩展接受的答案,还可以使用 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 };
    
        3
  •  0
  •   rookieCoder    4 年前

    这是我的问题陈述,我想把几个接口的属性类型合并成一个类型,这就是我所做的

    interface Fruit {
    name : string
    type : "Apple"
    }
    
    interface Fruit2 {
    name : string
    type : "Mango"
    }
    
    type FruitTypes = Fruit["type"] | Fruit2["type"]
    
    interface main {
    PK : string,
    SK :string,
    Type : FruitTypes 
    }
    
    const obj:main = {
    PK :"Some PK",
    SK :"Some SK",
    Type: "Mango"  // it can either be mango or apple only as in Fruit and Fruit2
    }
        4
  •  0
  •   Gabriel Petersson    4 年前

    获取所有值,由于 keyof Colors 返回所有键的列表,该列表依次获取 Colors 界面

    interface Colors {
      white: "#fff"
      black: "#000"
    }
    
    type ColorValues = Colors[keyof Colors]
    // ColorValues = "#fff" | "#000"
    
        5
  •  -3
  •   Noone    10 年前

    接口类似于对象的定义。那么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'
    
    推荐文章