Record<K, T>嗨,TypeScript和{ [key: K]: T }in TypeScript有什么區別?例如,它們在下面的代碼中似乎作業相同。
const obj1: Record<string, number> = {a: 1, b: 2};
const obj2: { [key: string]: number } = {a: 1, b: 2};
它們之間有什么區別嗎?
uj5u.com熱心網友回復:
您的情況沒有區別,但可以使用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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484027.html
上一篇:未檢測到聯合型別
