TypeScript 中的 Record<K, T> 和 { [key: K]: T } 有什么区别?
What is the difference between Record<K, T> and { [key: K]: T } in TypeScript?
嗨,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};
它们有什么区别吗?
您的情况没有区别,但可以使用 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)
嗨,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};
它们有什么区别吗?
您的情况没有区别,但可以使用 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)