首页 > 解决方案 > 在 TypeScript 中获取类型键

问题描述

假设我们有这种类型:

export type UsersSchema = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
};

有没有办法让这个伪代码工作:

Object.keys(UsersSchema)理想情况下会产生:['id', 'firstName', 'lastNight', 'email']

显然UsersSchema不是一个值,所以上面不起作用......

标签: typescript

解决方案


该类型在运行时不存在。

但是,(很大程度上依赖于这个漂亮的答案,因为它使用递归条件类型,所以需要 TS4.x),您可以创建一个元组类型来强制使用所需名称的元组。

所以:

type TupleUnion<U extends string, R extends string[] = []> = {
    [S in U]: Exclude<U, S> extends never 
                ? [...R, S] 
                : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U] & string[];


export type UsersSchema = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
};

const allKeysOfUsersSchema: TupleUnion<keyof UsersSchema> = 
    ["id", "firstName", "lastName", "email"]; //OK

const wrongKeysOfUsersSchema: TupleUnion<keyof UsersSchema> = 
    ["monkey", "firstName", "lastName", "email"]; //error

const missingKeysOfUsersSchema: TupleUnion<keyof UsersSchema> = 
    ["id", "firstName", "lastName"]; //error

const tooManyKeysOfUsersSchema: TupleUnion<keyof UsersSchema> = 
    ["id", "firstName", "lastName", "email", "cat"]; //error

好的......所以你必须手动维护这个单独的元组,但至少如果事情发生变化,编译器会推动你采取补救措施,因此保持类型安全。

游乐场链接


推荐阅读