【问题标题】:What does it mean in typescript: SomeInterface['someKey'][string]在打字稿中是什么意思:SomeInterface['someKey'][string]
【发布时间】:2021-07-09 21:33:24
【问题描述】:

函数会返回的数据类型SomeInterface['someKey'][string],是什么意思?实际的数据实例如何?这是一个对象吗?一个数组?

export const getSomething = (param: string): SomeInterface['someKey'][string] => { 
... 
}

【问题讨论】:

    标签: typescript interface key


    【解决方案1】:

    给定一个非空类型T 和类键类型K,它是T 的键(或此类键类型的union),T[K] 类型是indexed access type表示该属性键的值类型(或这些属性值类型的联合)。

    或者,换句话说,如果T是值t的类型,而K是值K的类型,那么T[K]是t[k]的类型。

    例如:

    let s = "hello"; // let s: string;
    const l = "length"; // const l: "length"
    const n = s[l]; // const n: number;
    type N = string["length"]; // type N = number;
    

    所以s 的类型为string,l 的类型为"length"(字符串literal type),s[l] 的类型为number。这意味着string["length"] 的类型与number 相同。


    回到您的问题:SomeInterface['someKey'][string] 类型因此是您获取类型为SomeInterface 的值(称为si)并使用@987654348 类型的键索引到它的类型@(所以,si.someKey),然后使用string 类型的键将索引索引到that(所以,si.someKey.xyz 假设xyz 是si.someKey 的键)。像这样的:

    function foo(si: SomeInterface) {
      const sis = si.someKey; // SomeInterface['someKey']
      const k = Object.keys(sis)[0]; // string
      return sis[k]; // SomeInterface['someKey'][string];
    }
    

    这里,函数foo()将返回一个SomeInterface['someKey'][string]类型的值。


    现在,至于究竟是什么类型,这完全取决于SomeInterface 的定义。显然它有一个名为someKey 的键,并且该键的属性有一个字符串index signature。

    例如,如果它看起来像这样:

    interface SomeInterface {
      someKey: {
        [k: string]: Date
      }
      someOtherKey: number;
    }
    

    那么SomeInterface["someKey"][string] 就是Date。

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2021-04-24
      • 2018-09-12
      • 2021-04-21
      • 2021-01-02
      • 2021-03-27
      • 2019-12-19
      • 2016-12-02
      相关资源
      最近更新 更多