TS/TypeScript 中,把对象的所有键/值变成一个联合类型 Union Type

784 阅读1分钟

要把一个对象的所有键、值组合成一个联合类型,需要三步骤:

  1. 定义一个只读对象
  2. 使用 keyof typeof 得到对象的所有键类型
  3. 使用键去得到联合类型
// 👇️ 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;

这里是利用 const 断言,它会尽量将类型特定化,具体见官方文档:const assertions

当然,你只要保持这个对象只读就可以,因此可以用其他方式,比如:

interface O {
  readonly name: string;
  readonly country: string;
}

const obj: O = {
  name: 'Tom',
  country: 'Chile',
};

为什么必须是只读的,主要是防止对象在中途被篡改,那么得到的联合类型就不准确,因此 TypeScript 才加上如此限制

REFERENCE

[1] bobbyhadz.com/blog/typesc…