TypeScript 中的 Record<K, T> 和 { [key: K]: T } 有什么区别?

问题描述 投票:0回答:2

嗨,TypeScript 中的

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

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

他们之间有什么区别吗?

typescript typescript-typings
2个回答
15
投票

您的情况没有区别,但可以使用

Record
做更多事情。考虑官方示例

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) 


0
投票

仍然可以写成[key in CatName]: CatInfo,这里没有提及。尽管对于某些人来说,记录语法似乎更符合逻辑,但我不同意。对我来说,与实际物体的相似性更有意义,也更容易阅读。

© www.soinside.com 2019 - 2024. All rights reserved.