Typescript类型体操 - Length of Tuple

题目

中文

创建一个通用的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;

在线演示

posted @ 2022-09-02 23:28  Laggage  阅读(42)  评论(0编辑  收藏  举报