08. Length
문제
For given a tuple, you need create a generic Length
, pick the length of the tuple.
For example:
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
풀이
풀이는 너무나 쉽다! 객체의 인덱스에 인위적으로 접근해서 해당 값의 타입을 가져올 수 있다는 것만 알고 있으면 된다.
// 0. 시작
type Length<T> = ...
// 1. 베열에 length 프로퍼티에 접근하자
// 이렇게 되면 T에 length 프로퍼티가 없다고 에러가 나온다.
type Length<T> = T['length']
// 2. T에 length 프로퍼티가 있는지 확인하자
type Lenfth<T extends { length: number }> = T['length']
// 3. 이렇게 하면 좋아보이지? 하지만 이건 별로다. 왜? 그냥 제한을 배열로 걸면 되기 때문
type Length<T extends any[]> = T['length']
Last updated
Was this helpful?