TypeScript

[ TypeScript ] type-challenges-00018-easy-tuple-length

만두맨두 2023. 8. 1. 21:17

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']를 통해 타입의 길이를 구한다.