Typescript类型体操 - PickByType

题目

中文

找出T中类型为U的属性

示例:

type OnlyBoolean = PickByType<
    {
        name: string;
        count: number;
        isReadonly: boolean;
        isEnable: boolean;
    },
    boolean
>; // { isReadonly: boolean; isEnable: boolean; }

English

From T, pick a set of properties whose type are assignable to U.

For Example

type OnlyBoolean = PickByType<
    {
        name: string;
        count: number;
        isReadonly: boolean;
        isEnable: boolean;
    },
    boolean
>; // { isReadonly: boolean; isEnable: boolean; }

答案

type PickByType<T, U> = { [P in keyof T as T[P] extends U ? P : never]: T[P] };

在线演示

posted @ 2022-09-21 00:44  Laggage  阅读(43)  评论(0编辑  收藏  举报