타입 챌린지 55 - Union to Intersection

소파의 벨로그·2025년 6월 19일

타입챌린지

목록 보기
117/131

문제 링크

문제

상향된 유틸타입 UnionToIntersection<U>을 구현하라

Implement the advanced util type UnionToIntersection<U>

다른 사람의 풀이

type UnionToIntersection<U> =
(U extends any ? (arg: U) => any : never) extends ((arg: infer I) => void) ? I : never

풀이

관련 개념

관련 ts 문서

지금껏 extends로 분배법칙을 작성하면 유니온 타입으로 작성된다고 생각했다.

그러나, 공변성이 있는 인자의 경우, extends로 분배법칙을 작성하면 유니온 타입이 아닌 intersection(&)으로 합쳐진다.

strictFunctionTypes이 켜져있는 경우에는 인자는 공변성을, 꺼져있는 경우에 인자는 이변성(공변성+반공변성)을 띈다

이변성을 띄는 경우에도 intersection이 구현된다

참고자료

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

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#type-inference-in-conditional-types

0개의 댓글