반응형
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가 나온다.
반응형
'✍ 공부 > TypeScript' 카테고리의 다른 글
[type-challenges] Awaited (0) | 2023.05.23 |
---|---|
[type-challenges] Exclude (0) | 2023.05.23 |
[type-challenges] First of Array (0) | 2023.05.23 |
[type-challenges] Tuple to Object (0) | 2023.05.16 |
[type-challenges] Readonly (0) | 2023.05.16 |