在 TypeScript 中从对象的键创建类型

在 TypeScript 中从对象的键创建类型

Create a Type from an object’s Keys in TypeScript

使用keyof typeof语法从对象的键创建类型,例如
type Keys = keyof typeof person. keyof typeof语法返回一个类型,该类型将对象的所有键表示为字符串。

索引.ts
const person = { name: 'Tom', age: 30, country: 'Chile', }; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = string | number type Values = typeof person[Keys];

我们使用
keyof typeof
从对象的键创建类型。

如果您需要获取表示另一种类型的键的类型,您可以使用keyof MyType.
索引.ts
type Person = { name: string; age: number; country: string; }; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof Person;

请注意,我们没有使用
typeof,因为Person它是一个类型而不是一个对象。

如果需要获取对象值的类型,请在定义对象时使用
const 断言

索引.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👈️ const assertion // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = "Tom" | 30 | "Chile" type Values = typeof person[Keys];

as const语法使对象具有属性readonly这意味着不能更改值。

索引.ts
// 👇️ const person: { // readonly name: "Tom"; // readonly age: 30; // readonly country: "Chile"; // } const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👈️ const assertion
这很有用,因为 TypeScript 能够将值的类型设置为特定文字。

如果我们不使用 const 断言,我们会得到更多的泛型类型,例如
stringand number

索引.ts
// 👇️ const person: { // name: string; // age: number; // country: string; // } const person = { name: 'Tom', age: 30, country: 'Chile', };

如果您需要包含对象值的联合类型,这可能不是您想要的。

索引.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👇️ type Keys = "name" | "age" | "country" type Keys = keyof typeof person; // 👇️ type Values = "Tom" | 30 | "Chile" type Values = typeof person[Keys];

您可以使用方括号语法获取任何对象值的类型。

索引.ts
const person = { name: 'Tom', age: 30, country: 'Chile', } as const; // 👇️ type V1 = "Tom" type V1 = typeof person['name']; // 👇️ type V2 = 30 type V2 = typeof person['age']; // 👇️ type V3 = "Chile" type V3 = typeof person['country'];