[TypeScript] Type Challenges #18 - Length of Tuple

95 阅读1分钟

题目描述

创建一个Length泛型,这个泛型接受一个只读的元组,返回这个元组的长度。

例如:

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

题解

// ============= Test Cases =============
import type { EqualExpect } from './test-utils'

const tesla = ['tesla''model 3''model X''model Y'as const
const spaceX = ['FALCON 9''FALCON HEAVY''DRAGON''STARSHIP''HUMAN SPACEFLIGHT'as const

type cases = [
  Expect<Equal<Length<typeof tesla>, 4>>,
  Expect<Equal<Length<typeof spaceX>, 5>>,
  // @ts-expect-error
  Length<5>,
  // @ts-expect-error
  Length<'hello world'>,
]


// ============= Your Code Here =============
type Length<T extends readonly unknown[]> = T['length']

1、T extends readonly unknown[]约束传入的T必须是一个只读的数组类型

2、T['length']:元组实际上是一种特殊的数组类型,它继承了数组的很多特性,其中就包括length属性。length属性用于表示元组中元素的个数