# 从对象中的值或键创建联合类型
用于as const
将对象的属性设置为readonly
。
用于keyof typeof
获取对象中键的类型。
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";}
const obj = {
name: 'Tom',
country: 'Chile',
} as const;
// 👇️ type UValues = "Tom" | "Chile"
type UValues = typeof obj[keyof typeof obj];
// 👇️ type UKeys = "name" | "country"
type UKeys = keyof typeof obj;
as const
该语法在 TypeScript as const 中称为 const 断言 (opens new window)。
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";}
const obj = {
name: 'Tom',
country: 'Chile',
} as const;
// ⛔️ Error: Cannot assign to 'name' because it is a
// read-only property.
obj.name = 'James';
参考文章: