00018-easy-tuple-length
[ 문제 설명 ]
For given a tuple, you need create a generic `Length`, pick the length of the tuple
[ 문제 ]
type Length<T> = any
[ 예시 ]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
튜플(readonly 배열) 타입의 길이를 가져올 수 있는 Length 타입을 정의하는 문제입니다.
사실 이번 문제의 설명이라고 하면,,, 어떻게 길이를 가져올 수 있는가에 대한 설명일텐데요...
그 설명을 00014-easy-first에서 다 해버렸습니다.. 🥲
아래 링크에 자세히 설명되어 있으니까 한 번씩 봐주시면 좋을 것 같아요 : )
[ TypeScript ] type-challenges - 00014-easy-first
00014-easy-first [ 문제 설명 ] Implement a generic `First` that takes an Array `T` and returns its first element's type. [ 문제 ] type First = any [ 예시 ] type arr1 = ['a', 'b', 'c'] type arr2 = [3, 2, 1] type head1 = First // expected to be 'a
gomandoogomandoo.tistory.com
[ 정답 ]
type Length<T extends readonly any[]> = T['length']
1. T에 튜플이 들어오기 때문에 readonly any[]를 extends 시켜준다.
2. T['length']를 통해 타입의 길이를 구한다.
'TypeScript' 카테고리의 다른 글
[ TypeScript ] type-challenges - 00014-easy-first (0) | 2023.07.24 |
---|---|
[ TypeScript ] type-challenges - 00011-easy-tuple-to-object (0) | 2023.07.21 |
[ TypeScript ] type-challenges - 00007-easy-readonly (0) | 2023.07.08 |
[ TypeScript ] type-challenges - 00004-easy-pick (0) | 2023.07.06 |
[TypeScript] 지금까지 만난 타입스크립트 룰 정리본 (0) | 2023.04.08 |