Language/Typescript
타입챌린지 : 3062-Shift (medium)
hsloth
2023. 5. 22. 14:32
이 글은 제가 타입챌린지를 하면서 해석한 내용을 적는 글입니다. 틀린 내용이 있으면 댓글 달아주시면 감사하겠습니다.
https://github.com/type-challenges/type-challenges/blob/main/questions/03062-medium-shift/README.md
GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
Collection of TypeScript type challenges with online judge - GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
github.com
shift란 큐에서 큐 맨 앞의 원소를 빼내는 것이다. 이걸 타입으로 구현하면 된다.
맨 앞 원소를 제외한 나머지 배열을 리턴하는 타입을 만들면 된다.
정~~~말 간단하다. Easy 난이도에 들어가도 될 만큼...
type Shift<T extends any[]> = T extends [infer F, ...infer O] ? O : [];
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
// @ts-expect-error
Shift<unknown>,
Expect<Equal<Shift<[]>, []>>,
Expect<Equal<Shift<[1]>, []>>,
Expect<Equal<Shift<[3, 2, 1]>, [2, 1]>>,
Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,
]
type Shift<T extends any[]> : Shift라는 타입을 정의하는데 T는 배열이라고 조건을 건다.
T extends [infer F, ...infer O] ? O : [] : T가 첫 원소 F와 나머지 배열 O로 나누어진다면, F를 제외한 나머지 배열 O를 리턴한다. 아니라면 빈 배열을 리턴한다.