[Typescript] 41. 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

 

Not fully understand how the solution works.

/* _____________ Your Code Here _____________ */
type IsUnion<T, C = T> = [T] extends [never] 
  ? false
  : T extends C 
    ? [C] extends [T] 
      ? false
      : true
    : never;
// [T]: [void | "" | null | undefined]
// [C]: [void] | [""] | [null] | [undefined]
type x= IsUnion<undefined | null | void | ''> 

/* _____________ Test Cases _____________ */
import type { 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>>,
]

 

posted @   Zhentiw  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-09-30 [Angular] Overlay CDK
2020-09-30 [Typescript] “keyof”, Generics and Lookup Types
2020-09-30 [TypeScript] “typeof” Type Queries
2020-09-30 [Javascript] Broadcaster + Operator + Listener pattern -- 4. Concat
2020-09-30 [Javascript] Broadcaster + Operator + Listener pattern -- 3 Stop with condition
2020-09-30 [Typescript] Typing “this” and “noImplicitThis”
2017-09-30 [Javascript AST] 4. Continue: Report ESLint error
点击右上角即可分享
微信分享提示