#1097Medium

IsUnion

Implement a type `IsUnion`, which takes an input type `T` and returns whether `T` resolves to a union type. Learn union type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement an IsUnion<T> type that detects whether a given type is a union type, correctly handling edge cases like never, any, unknown, and unions that collapse into a single type (e.g., string | 'a' resolves to string).

Challenge Instructions: IsUnion

Medium

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

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
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<E

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type IsUnion<T, Copy = T> =
  [T] extends [never]
    ? false
    : T extends T
      ? [Copy] extends [T]
        ? false
        : true
      : never;

How it works:

This challenge helps you understand distributive conditional types and the mechanics of union type detection, and how to apply these patterns in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts