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

TypeScript中记录<K,T>和{[键:K]:T}之间有什么区别?

  •  0
  • tmokmss  · 技术社区  · 3 年前

    嗨,这两者有什么区别 Record<K, T> { [key: K]: T } 在TypeScript中? 例如,在下面的代码中,它们似乎工作相同。

    const obj1: Record<string, number> = {a: 1, b: 2};
    const obj2: { [key: string]: number } = {a: 1, b: 2};
    

    他们之间有什么区别吗?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Ricky Mo    3 年前

    您的情况没有什么不同,但可以使用 Record 。考虑一下 official example

    interface CatInfo {
      age: number;
      breed: string;
    }
     
    type CatName = "miffy" | "boris" | "mordred";
     
    const cats: Record<CatName, CatInfo> = {
      miffy: { age: 10, breed: "Persian" },
      boris: { age: 5, breed: "Maine Coon" },
      mordred: { age: 16, breed: "British Shorthair" },
    };
    

    您不能将其替换为

    const cats2: {[key:CatName]: CatInfo} = {
        miffy: { age: 10, breed: "Persian" },
        boris: { age: 5, breed: "Maine Coon" },
        mordred: { age: 16, breed: "British Shorthair" },
    };
    

    因为这会给你带来错误 An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.(1337)