代码之家  ›  专栏  ›  技术社区  ›  Paulo Fernando

带`in`的Typescript索引签名?

  •  0
  • Paulo Fernando  · 技术社区  · 3 年前

    我在学打字,这两种类型有什么区别吗?

    type KeyInString =  {
      [key in string]: string
    }
    
    type KeyColonString =  {
      [key: string]: string
    }
    
    const test2: KeyColonString = {
      random: 'ASDAS',
      more: "asdadsa"
    }
    
    const test1: KeyInString = {
      random: 'ASDAS',
      more: "asdadsa"
    }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   wonderflame    3 年前

    第一个 in 被调用 mapped types 另一个是 index signature 。

    不同的是,您不能使用 index signature 具有泛型或文字类型。

    type Case1<T extends string> = {
      [key: T]: string; // An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
    };
    
    type Case2 = {
      [key: 'a' | 'b']: string; // An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
    };
    

    然而,它在 mapped types :

    type Case1<T extends string> = {
      [key in T]: string; // no error
    };
    
    type Case2 = {
      [key in 'a' | 'b']: string; // no error
    };
    ```
    
    推荐文章