【问题标题】:getting the type of a types properties获取类型属性的类型
【发布时间】:2019-09-28 21:44:02
【问题描述】:

我目前有一个从第三方提取的类型。我想获取该类型的属性的类型。用于打字稿。

例如


type GivenType = {
    prop: string;
}

type desiredType = <<getTypeOf GivenType.prop>>

desiredType === string // true;

我正在寻找&lt;&lt;getTypeOf GivenType.prop&gt;&gt; 的实际语法

我主要查看了 typescript 文档,发现提取类型通常作用于对象或接口。诸如typeofreturnType 之类的命令

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    你可以像这样获取属性的类型:

    type SomePropertyType = SomeType["SomeProperty"];
    

    这是一个“索引访问运算符”; this documentation section有详细信息。

    E.g.

    // number
    type LengthPropertyType = String["length"];
    
    // () => number
    type GetFullYearType = Date["getFullYear"];
    
    type GivenType = {
        prop: string;
    }
    
    // string
    type DesiredType = GivenType["prop"];
    

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 2020-01-29
      • 2015-07-28
      • 2015-02-15
      • 2012-12-17
      • 2022-08-11
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多