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

Typescript类型体操 - StartsWith

时间:2022-09-21 01:00:06浏览次数:105  
标签:StartsWith Typescript false true extends 体操 expected type

题目

中文

实现StartsWith<T, U>,接收两个 string 类型参数,然后判断T是否以U开头,根据结果返回truefalse

例如:

type a = StartsWith<'abc', 'ac'>; // expected to be false
type b = StartsWith<'abc', 'ab'>; // expected to be true
type c = StartsWith<'abc', 'abcd'>; // expected to be false

English

Implement StartsWith<T, U> which takes two exact string types and returns whether T starts with U

For example

type a = StartsWith<'abc', 'ac'>; // expected to be false
type b = StartsWith<'abc', 'ab'>; // expected to be true
type c = StartsWith<'abc', 'abcd'>; // expected to be false

答案

递归(第一时间想到的, 不是最优解)

type StartsWith<
    T extends string,
    U extends string
> = T extends `${infer L}${infer R}`
    ? U extends `${infer UL}${infer UR}`
        ? UL extends L
            ? StartsWith<R, UR>
            : false
        : true
    : U extends ''
    ? true
    : false;

最优解

type StartsWith<T extends string, U extends string> = T extends `${U}${any}`
    ? true
    : false;

在线演示

标签:StartsWith,Typescript,false,true,extends,体操,expected,type
From: https://www.cnblogs.com/laggage/p/type-challenge-starts-with.html

相关文章

  • Typescript类型体操 - RemoveIndexSignature
    题目中文实现RemoveIndexSignature<T>,将索引字段从对象中排除掉.示例:typeFoo={[key:string]:any;foo():void;};typeA=RemoveIndexSignature<......
  • Typescript类型体操 - PickByType
    题目中文找出T中类型为U的属性示例:typeOnlyBoolean=PickByType<{name:string;count:number;isReadonly:boolean;isE......
  • 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......