[Typescript] 151. Medium IsUnion
Implement a type IsUnion
, which takes an input type T
and returns whether T
resolves to a union type.
For example:
type case1 = IsUnion<string> // false
type case2 = IsUnion<string | number> // true
type case3 = IsUnion<[string | number]> // false
Answer:
export type Equal<T, U> = (<P>(x: P) => P extends T ? 1 : 2) extends <P>(
x: P
) => P extends U ? 1 : 2
? true
: false;
type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true;
type IsUnion<T> = NotEqual<[T] & T, (T extends T ? [T] : never) & T>;
/* _____________ Test Cases _____________ */
import type { NotEqual, Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<IsUnion<string>, false>>,
Expect<Equal<IsUnion<string | number>, true>>,
Expect<Equal<IsUnion<'a' | 'b' | 'c' | 'd'>, true>>,
Expect<Equal<IsUnion<undefined | null | void | ''>, true>>,
Expect<Equal<IsUnion<{ a: string } | { a: number }>, true>>,
Expect<Equal<IsUnion<{ a: string | number }>, false>>,
Expect<Equal<IsUnion<[string | number]>, false>>,
// Cases where T resolves to a non-union type.
Expect<Equal<IsUnion<string | never>, false>>,
Expect<Equal<IsUnion<string | unknown>, false>>,
Expect<Equal<IsUnion<string | any>, false>>,
Expect<Equal<IsUnion<string | 'a'>, false>>,
Expect<Equal<IsUnion<never>, false>>,
]
We use string
as an example
[T] & T
is [string] & string
(T extends T ? [T] : never) & T
is also [string] & string
If it's union, for example
string | number
[T] & T
is [string | number] & (string | number)
(T extends T ? [T] : never) & T
is ([string]|[number]) & (string | number)
So [string | number]
is not equal to ([string] | [number])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-05-13 [AWS] Talk: Getting started with AWS identity
2020-05-13 [Python] Read from a File in Python
2020-05-13 [Javascript] Broadcaster + Operator + Listener pattern -- 01
2019-05-13 [Functional Programming] Add, Mult, Pow, isZero
2018-05-13 [React] Update Application State with React Apollo ApolloConsumer Component
2016-05-13 [Javascript] Writing conventional commits with commitizen
2016-05-13 [Javascript] Automating Releases with semantic-release