[英]Get Type keys in TypeScript
Lets say we have this Type:假设我们有这种类型:
export type UsersSchema = {
id: number;
firstName: string;
lastName: string;
email: string;
};
Is there a way to make this pseudo-code work:有没有办法让这个伪代码工作:
Object.keys(UsersSchema)
which would ideally yield: ['id', 'firstName', 'lastNight', 'email']
Object.keys(UsersSchema)
理想情况下会产生: ['id', 'firstName', 'lastNight', 'email']
Obviously UsersSchema
is not a value, so the above does not work...显然
UsersSchema
不是一个值,所以上面的不起作用......
The type doesn't exist at run time.该类型在运行时不存在。
However, (leaning heavily on this beautiful answer , which will require TS4.x because of its use of recursive conditional types), you can create a tuple type that enforces a tuple with the required names.但是,(严重依赖这个漂亮的答案,因为它使用递归条件类型,它需要 TS4.x),您可以创建一个元组类型来强制使用所需名称的元组。
So:所以:
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
OK... so you'll have to maintain this separate tuple, manually, but at least if things change, the compiler will push you into remedial action, so type-safety is maintained.好的...因此您必须手动维护这个单独的元组,但至少如果情况发生变化,编译器会促使您采取补救措施,从而保持类型安全。
You can use keyof
type operator.您可以使用
keyof
类型运算符。
export type UsersSchema = {
id: number;
firstName: string;
lastName: string;
email: string;
};
type Keys = keyof UsersSchema // "id" | "firstName" | "lastName" | "email"
in addition to hwasurr answer you probably need to put the keys in parenthesis to get the right type除了hwasurr answer 你可能需要将键放在括号中以获得正确的类型
the array of keys:键数组:
type Keys = (keyof UsersSchema)[]
// ("id" | "firstName" | "lastName" | "email")[]
Lets say we have this Type:假设我们有这种类型:
export type UsersSchema = {
id: number;
firstName: string;
lastName: string;
email: string;
};
Is there a way to make this pseudo-code work:有没有办法让这个伪代码工作:
Object.keys(UsersSchema)
which would ideally yield: ['id', 'firstName', 'lastNight', 'email']
Object.keys(UsersSchema)
理想情况下会产生: ['id', 'firstName', 'lastNight', 'email']
Obviously UsersSchema
is not a value, so the above does not work...显然
UsersSchema
不是一个值,所以上面不起作用......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.