✍ 공부/TypeScript

[type-challenges] Length of Tuple

Po_tta_tt0 2023. 5. 23. 18:15
반응형

 

 

 

0. 문제

배열(튜플)을 받아 길이를 반환하는 제네릭 Length<T>를 구현하세요.

 

 

 

1. 설명

/* _____________ Your Code Here _____________ */

type Length<T extends readonly any[]> = T['length']

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/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'>,
]

type Length<T extends readonly any[]> = T['length']

 

 

'length'란?
(property) ReadonlyArray<any>.length: number Gets the length of the array. This is a number one higher than the highest element defined in an array.
Readonly 배열.length를 하면 그 배열의 길이만큼의 number가 나온다.

반응형