typescript - 在 TypeScript 中获取类型键
问题描述
假设我们有这种类型:
export type UsersSchema = {
id: number;
firstName: string;
lastName: string;
email: string;
};
有没有办法让这个伪代码工作:
Object.keys(UsersSchema)
理想情况下会产生:['id', 'firstName', 'lastNight', 'email']
显然UsersSchema
不是一个值,所以上面不起作用......
解决方案
该类型在运行时不存在。
但是,(很大程度上依赖于这个漂亮的答案,因为它使用递归条件类型,所以需要 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
好的......所以你必须手动维护这个单独的元组,但至少如果事情发生变化,编译器会推动你采取补救措施,因此保持类型安全。
推荐阅读
- java - 从字符串数组对象中检索每个键值
- android - 我可以使用 kotlin 删除文件而不复制到内部存储上的 ../recycle_bin 文件夹吗
- javascript - 当函数导出到不同的 JS 文件时,函数打印两次的结果
- xamarin - Xamarin Datapicker 如何将其自定义为日历图像
- javascript - 单击浏览器中的后退按钮时如何防止导航返回?
- javascript - 有没有办法在 react-js 中扩展另一个类而不是 Component 类
- c++ - 为什么“if”不在循环中执行?
- php - 如何修复水平的导航栏在WordPress中应该是垂直的?
- c++ - wxWindows 2.4.2 配置失败说检查工具包...配置:错误:请最多指定一个工具包
- python - Flask JWT:没有 @jwt_required 的 get_jwt_identity() 总是返回 Non