타입 챌린지 18142 - All

소파의 벨로그·2025년 5월 20일

타입챌린지

목록 보기
89/131

문제 링크

문제

list의 모든 요소가 두 번째 파라미터와 모두 같다면 true를, 안맞는 것이 하나라도 있다면 false를 반환하라.

Returns true if all elements of the list are equal to the second parameter passed in, false if there are any mismatches.

내 풀이

type All<T extends any[],U> =
  T extends [infer First,...infer Rest]?
    Equal<First,U> extends false?
      false
      :All<Rest,U>
    :true

T 안의 요소가 같은지를 판단하기 위해 @type-challenges/utilsEqauls를 사용했다.
만약 하나라도 다른 값이 있다면 false, 재귀적으로 호출하다가 빈 배열이 들어온다면(마지막 재귀 호출이라면) true를 반환한다.

다른 사람의 풀이

type All<T extends any[], N> = T[number] extends N ? true : false;

eqaul이 엄격하지 않을 때 (ex:1과 1|2는 같음) 허용되는 풀이이다.

참고자료

https://github.com/type-challenges/type-challenges/issues/20895

0개의 댓글