首页 > 其他分享 >Typescript类型体操 - PickByType

Typescript类型体操 - PickByType

时间:2022-09-21 00:55:06浏览次数:80  
标签:Typescript isEnable isReadonly boolean 体操 PickByType type

题目

中文

找出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] };

在线演示

标签:Typescript,isEnable,isReadonly,boolean,体操,PickByType,type
From: https://www.cnblogs.com/laggage/p/type-challenge-pick-by-type.html

相关文章

  • Typescript类型体操 - MinusOne
    题目中文给定一个正整数作为类型的参数,要求返回的类型是该数字减1。例如:typeZero=MinusOne<1>;//0typeFiftyFour=MinusOne<55>;//54EnglishGivenanu......
  • typescript-变量
    1.变量赋值了类型就不能赋值其他类型1leta:number;2letb:string;3a=10;45//不可以6//a="assdf";7b="123"2.如果变量的声明和赋值是同时......
  • Typescript类型体操 - PercentageParser
    题目中文实现类型PercentageParser。根据规则/^(\+|\-)?(\d*)?(\%)?$/匹配类型T。匹配的结果由三部分组成,分别是:[正负号,数字,单位],如果没有匹配,则默认是空字符串......
  • Typescript类型体操 - DropChar
    题目中文从字符串中剔除指定字符。例如:typeButterfly=DropChar<'butterfly!',''>;//'butterfly!'EnglishDropaspecifiedcharfromastring.......
  • Typescript类型体操 - ReplaceKeys
    题目中文实现一个ReplaceKeys类型,这个类型可以替换联合类型中指定属性的类型,如果联合类型中的某个类型没有这个属性,那就跳过;ReplaceKeys接受3个泛型参数.例如......
  • 在 TypeScript 中指定 event.target 的类型
    在TypeScript中指定event.target的类型让我们解决使用ClassList和dataset等属性时出现的错误!案件由来本文出现的所有错误都是基于eslint产生的错误。我想通过......
  • [Typescript] 18. Medium - Deep Readonly
    Implementageneric DeepReadonly<T> whichmakeeveryparameterofanobject-anditssub-objectsrecursively-readonly.Youcanassumethatweareonlydea......
  • [Typescript] 17. Medium - Readonly 2
    Implementageneric MyReadonly2<T,K> whichtakestwotypeargument T and K.K specifythesetofpropertiesof T thatshouldsettoReadonly.When K......
  • Typescript类型体操 - kebab case
    题目中文将camelCase或PascalCase的字符串转换为kebab-case的风格示例:typeFooBarBaz=KebabCase<'FooBarBaz'>;constfoobarbaz:FooBarBaz='foo-bar-baz'......
  • Typescript类型体操 - String to Union
    题目中文实现一个将接收到的String参数转换为一个字母Union的类型。例如typeTest='123';typeResult=StringToUnion<Test>;//expectedtobe"1"|"2"|......