두 배열(T와 U)의 길이를 비교하는 CompareArrayLength를 구현하라
Implement CompareArrayLength to compare two array length(T & U).
type CompareArrayLength<T extends any[], U extends any[]> =
T['length'] extends U['length']?0:
T['length'] extends 0?-1:
U['length'] extends 0?1:
T extends [infer _,...infer TRest]?
U extends [infer _,...infer URest]?
CompareArrayLength<TRest,URest>
:never
:never
T와 U의 길이가 같다면 0,
재귀적으로 호출했을 때 T가 먼저 길이 0에 도달했다면 -1,
재귀적으로 호출했을 때 U가 먼저 길이 0에 도달했다면 1을 반환한다.
만약 두 배열의 길이가 둘 다 0이 아니라면, 맨 앞을 제외한 나머지 배열을 T와 U에 넣어 재귀적으로 호출한다.
type CompareArrayLength<T extends unknown[], U extends unknown[]> = T['length'] extends U['length']
? 0
: `${U['length']}` extends keyof T ? 1 : -1;
풀이
T의 keyof는 ${0}|${1}|...|${T['length']-1}이다
이때 U['length']가 keyof T에 들어간다면 U가 T보다 작은 것이므로 1을, 그렇지 않다면 큰 것이므로 -1을 반환한다.
https://github.com/type-challenges/type-challenges/issues/34089