首页 > 其他分享 >Typescript类型体操 - Length of Tuple

Typescript类型体操 - Length of Tuple

时间:2022-09-02 23:33:56浏览次数:77  
标签:Typescript Tuple tesla Length expected FALCON model type

题目

中文

创建一个通用的Length,接受一个readonly的数组,返回这个数组的长度。

例如:

type tesla = ['tesla', 'model 3', 'model X', 'model Y']
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']

type teslaLength = Length<tesla> // expected 4
type spaceXLength = Length<spaceX> // expected 5

English

For given a tuple, you need create a generic Length, pick the length of the tuple

For example:

type tesla = ['tesla', 'model 3', 'model X', 'model Y']
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']

type teslaLength = Length<tesla>  // expected 4
type spaceXLength = Length<spaceX> // expected 5

答案

type Length<T extends readonly any[]> = T extends { length: infer U } ? U : never;

在线演示

标签:Typescript,Tuple,tesla,Length,expected,FALCON,model,type
From: https://www.cnblogs.com/laggage/p/16651686.html

相关文章

  • Typescript类型体操 - Tuple To Object
    题目中文传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。例如:consttuple=['tesla','model3','modelX','modelY']a......
  • [Typescript Challenges] 10. Medium - Include
    ImplementtheJavaScript Array.includes functioninthetypesystem.Atypetakesthetwoarguments.Theoutputshouldbeaboolean true or false.Forexa......
  • [Typescript Challenges] 7. Easy - Awaited
    IfwehaveatypewhichiswrappedtypelikePromise.Howwecangetatypewhichisinsidethewrappedtype?Forexample:ifwehave Promise<ExampleType> ho......
  • [Typescript Challenges] 4. Easy - First of Array
    Implementageneric First<T> thattakesanArray T andreturnsit'sfirstelement'stype.typearr1=['a','b','c']typearr2=[3,2,1]typehead1=F......
  • [Typescript Challenges] 5. Easy - Length of Tuple
    Forgivenatuple,youneedcreateageneric Length,pickthelengthofthetupleForexample:typetesla=['tesla','model3','modelX','modelY']typesp......
  • [Typescript Challenges] 6 Easy - Exclude
    Implementthebuilt-inExclude<T,U>Forexample:typeResult=MyExclude<'a'|'b'|'c','a'>//'b'|'c' /*_____________YourCodeHere_____________......
  • Typescript类型体操 - Readonly 2
    题目中文实现一个通用MyReadonly2<T,K>,它带有两种类型的参数T和K。K指定应设置为Readonly的T的属性集。如果未提供K,则应使所有属性都变为只读,就像普通的Readonly<T>一......
  • Typescript类型体操 - Pick
    题目要求实现TS内置的Pick<T,K>,但不可以使用它。从类型T中选择出属性K,构造成一个新的类型。例如:interfaceTodo{title:stringdescription:stringco......
  • [Typescript Challenges] 1. Easy - Pick
    Forexample:interfaceTodo{title:stringdescription:stringcompleted:boolean}typeTodoPreview=MyPick<Todo,'title'|'completed'>consttodo:......
  • [Typescript] 2. Easy -- readonly
    Forexample:interfaceTodo{title:stringdescription:string}consttodo:MyReadonly<Todo>={title:"Hey",description:"foobar"}todo.title=......