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;

在线演示

posted @ 2022-09-22 21:12  Laggage  阅读(97)  评论(0编辑  收藏  举报