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

Typescript类型体操 - Trim

时间:2022-09-04 23:34:47浏览次数:84  
标签:Trim Typescript extends 体操 World type infer

题目

中文

实现Trim<T>,它是一个字符串类型,并返回一个新字符串,其中两端的空白符都已被删除。

例如

type trimed = Trim<'  Hello World  '> // expected to be 'Hello World'

English

Implement Trim<T> which takes an exact string type and returns a new string with the whitespace from both ends removed.

For example

type trimmed = Trim<'  Hello World  '> // expected to be 'Hello World'

答案

type Trim<S extends string> = S extends `${' ' | '\n' | '\t'}${infer U}` ? Trim<U> : (S extends `${infer U}${' ' | '\n' | '\t'}` ? Trim<U> : S)

在线演示

标签:Trim,Typescript,extends,体操,World,type,infer
From: https://www.cnblogs.com/laggage/p/type-challenge-trim.html

相关文章

  • Typescript类型体操 - Trim Left
    题目中文实现TrimLeft<T>,它接收确定的字符串类型并返回一个新的字符串,其中新返回的字符串删除了原字符串开头的空白字符串。例如typetrimed=TrimLeft<'HelloWo......
  • Typescript类型体操 - Promise.all
    题目中文键入函数PromiseAll,它接受PromiseLike对象数组,返回值应为Promise<T>,其中T是解析的结果数组。constpromise1=Promise.resolve(3);constpromise2=42;cons......
  • Typescript类型体操 - Type Lookup
    题目中文有时,您可能希望根据某个属性在联合类型中查找类型。在此挑战中,我们想通过在联合类型Cat|Dog中搜索公共type字段来获取相应的类型。换句话说,在以下示例中,我们......
  • Typescript类型体操 - Chainable Options
    题目中文在JavaScript中我们经常会使用可串联(Chainable/Pipeline)的函数构造一个对象,但在TypeScript中,你能合理的给它赋上类型吗?在这个挑战中,你可以使用任意你喜欢的......
  • Typescript类型体操 - Tuple To Union
    题目中文实现泛型TupleToUnion<T>,它返回元组所有值的合集。例如typeArr=['1','2','3']typeTest=TupleToUnion<Arr>//expectedtobe'1'|'2'|'3'Eng......
  • [Typescript] 14. Easy - Parameters
    Implementthebuilt-inParametersgenericwithoutusingit.Forexample:constfoo=(arg1:string,arg2:number):void=>{}typeFunctionParamsType=MyPara......
  • [Typescript] 11. Medium - Equal
    ImplementtheEqual<T,U>Forexample:typeisEqual=Equal<1,1>//trueIdea: Parametertype: <P>(x:P)=>anyCheckPextendsT?1:2ThencheckPexte......
  • [Typescript] 12. Easy - Push
     Implementthegenericversionof Array.pushForexample:typeResult=Push<[1,2],'3'>//[1,2,'3'] /*_____________YourCodeHere_____________*/......
  • [Typescript] 13. Easy - Unshift
    Implementthetypeversionof Array.unshiftForexample:typeResult=Unshift<[1,2],0>//[0,1,2,] /*_____________YourCodeHere_____________*/t......
  • 模式匹配-让你 ts 类型体操水平暴增的套路
    Typescript支持泛型,也叫类型参数,可以对类型参数做一系列运算之后返回新的类型,这就是类型编程。因为类型编程实现一些逻辑还是有难度的,所以被戏称为类型体操。社区有用......