타입 챌린지 223 - IsAny

소파의 벨로그·2025년 7월 2일

타입챌린지

목록 보기
125/131

문제 링크

문제

때때라 당신이 any 타입을 가지고 있는지 판별하는 것은 유용하다. 이것은 특히 any value를 export 할 수 있는 서드 파티 타입스크립트 모듈과 함께 작업할 때 유용하다. 이것은 또한 implicitAny 체크를 하지 않을 때에도 알면 좋다.

그래서, T를 받아서 T가 any이면 true를 아니면 false를 반환하는 유틸리티 타입 IsAny<T>를 구현하라

Sometimes it's useful to detect if you have a value with any type. This is especially helpful while working with third-party Typescript modules, which can export any values in the module API. It's also good to know about any when you're suppressing implicitAny checks.

So, let's write a utility type IsAny<T>, which takes input type T. If T is any, return true, otherwise, return false.

풀이 1

type IsAny<T> = 0 extends (1 & T) ? true : false;

풀이 링크

왜인지는 모르겠지만, 싱글 타입 & any는 any로 취급이 된다.(관련 문서도 존재하지 않는다..)
그래서 전혀 겹치지 않는 타입인 0과 1을 any와 결합시켰을 때 확장 가능한지 확인하면 된다.

풀이 2

type IsAny<T> = [{}, T] extends [T, null] ? true : false;

풀이 링크

두 가지 조건을 모두 통과하면 true가 되는 방식이다
1) T에 {}를 대입할 수 있다.
2) null에 T를 대입할 수 있다.

1번 조건에서, T에 들어갈 수 있는 값은 any와 unknown,{}, 그리고 모든 객체의 키가 optional인 객체이다.

1번 조건을 만족하는 타입 중 2번 조건에서는 any만이 들어갈 수 있다.

참고자료

https://github.com/type-challenges/type-challenges/issues/232
https://github.com/type-challenges/type-challenges/issues/5794

0개의 댓글