# 从对象中的值或键创建联合类型

用于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';

参考文章:

从 TS 中对象的值或键创建联合类型 (opens new window)

更新时间: 2022年9月1日星期四下午2点59分