Typescript类型体操 - ObjectEntries
题目
中文
实现 Object.entries
的类型版本
示例:
interface Model {
name: string;
age: number;
locations: string[] | null;
}
type modelEntries = ObjectEntries<Model>; // ['name', string] | ['age', number] | ['locations', string[] | null];
English
Implement the type version of Object.entries
For example
interface Model {
name: string;
age: number;
locations: string[] | null;
}
type modelEntries = ObjectEntries<Model>; // ['name', string] | ['age', number] | ['locations', string[] | null];
答案
type ObjectEntries<
T,
R extends keyof T = keyof T,
RequiredT = { [K in keyof T]-?: T[K] }
> = R extends keyof RequiredT
? [R, [RequiredT[R]] extends [never] ? undefined : RequiredT[R]]
: never;