Sub topic 12
Edge cases: never, any, and non-distributive checks
This chapter assumes you can read and write generic type aliases and constraints. It also assumes you know how T extends U ? X : Y and { [K in keyof T]: ... } work, and that you have seen conditional types distribute over unions. Here you will learn what happens at the corners of those rules: never, any, unknown, and boolean. You will also learn how to turn distribution off on purpose.
Why the corners matter
Most helper types are tested with a handful of object types and string literals. They then break when a caller passes never from an exhausted switch. They can also break on any from an untyped library, or on boolean, which is secretly a union. The rules below are consistent, and each one follows from how distribution works.
A small test harness
The examples use two helpers so the compiler checks every claim. Equal compares two types exactly. Expect fails to compile unless its argument is true.
type Equal<A, B> =
(<X>() => X extends A ? 1 : 2) extends (<X>() => X extends B ? 1 : 2)
? true
: false;
type Expect<T extends true> = T;
type IsString<T> = T extends string ? true : false;
type Checks = [
Expect<Equal<IsString<"hi">, true>>,
Expect<Equal<IsString<unknown>, false>>,
Expect<Equal<IsString<never>, never>>,
Expect<Equal<IsString<any>, boolean>>,
Expect<Equal<IsString<string | number>, boolean>>,
];The last three lines are the surprising ones. The next sections explain each.
never is an empty union
A distributive conditional type applies its check to each member of a union and unions the results. never is the union with zero members. Distribution therefore runs zero times, and the result is the union of nothing, which is never.
type IsString<T> = T extends string ? true : false;
type R = IsString<never>; // never, not falseThe result is not false, because the check never ran. This is why a naive IsNever does not work:
type BadIsNever<T> = T extends never ? true : false;
type X = BadIsNever<never>; // never
type Y = BadIsNever<string>; // falseThe fix is the tuple wrapper. [T] is not a naked type parameter, so the conditional is not distributive. A one-element tuple holding never is a real type that can be compared.
type IsNever<T> = [T] extends [never] ? true : false;
type A = IsNever<never>; // true
type B = IsNever<string>; // false
type C = IsNever<void>; // falseTurning distribution off
Distribution happens only when the checked type is a naked type parameter. Anything that wraps it, such as [T], T[], or Promise<T>, switches distribution off. The tuple form is the common idiom because it adds no other meaning.
type ToArray<T> = T extends unknown ? T[] : never;
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type D1 = ToArray<string | number>; // string[] | number[]
type D2 = ToArrayNonDist<string | number>; // (string | number)[]
type N1 = ToArray<never>; // never
type N2 = ToArrayNonDist<never>; // never[]Two details are easy to miss:
- Distribution applies at instantiation. A union written inline, as in
("a" | "b") extends string ? 1 : 2, is checked as a whole because there is no type parameter to distribute. - The wrapper must appear on the checked side.
T extends [U]still distributes overT. Only[T] extends [U]does not.
boolean is a union
boolean is defined as true | false, so a distributive conditional splits it into two checks.
type Describe<T> = T extends true ? "yes" : "no";
type P = Describe<boolean>; // "yes" | "no"If you wanted a single answer for boolean, wrap the check. [boolean] extends [true] is false, so the result is "no". Enums that are unions of members behave the same way.
The built-in Exclude relies on this splitting, and its non-distributive version shows what is lost:
type MyExclude<T, U> = T extends U ? never : T;
type WrongExclude<T, U> = [T] extends [U] ? never : T;
type K1 = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"
type K2 = WrongExclude<"a" | "b" | "c", "a">; // "a" | "b" | "c"In K2 the whole union "a" | "b" | "c" is compared with "a". It is not assignable, so the union comes back unchanged. Distribution is what makes Exclude and Extract work member by member.
any picks both branches
any is assignable to and from nearly everything, so the compiler cannot choose a branch. When any is the checked type, the conditional returns the union of both branches.
type IsString<T> = T extends string ? true : false;
type Q = IsString<any>; // true | false, which is booleanThere is one exception. If the extends clause is itself any or unknown, the check always succeeds and only the true branch is used. That is why ToArray<any> is any[], not a union.
Wrapping in a tuple changes what any does. [any] extends [string] is just an assignability check, and any is assignable to string, so it returns the true branch.
| T | `T extends string ? true : false` | `[T] extends [string] ? true : false` | Column |
|---|---|---|---|
| `never` | `never` | `true` | |
| `any` | `boolean` | `true` | |
| `unknown` | `false` | `false` | |
| `string \ | number` | `boolean` | `false` |
The never row shows the main hazard. The wrapped form says true because never is assignable to every type. That is correct for assignability and surprising if you expected "is this type a string".
Detecting any
Sometimes you need to know that a type is any, for example to warn when a library hands you untyped data. The trick uses intersections. 1 & any is any, while 1 & T for any other T is either 1 or never.
type IsAny<T> = 0 extends 1 & T ? true : false;
type Checks = [
Expect<Equal<IsAny<any>, true>>,
Expect<Equal<IsAny<unknown>, false>>,
Expect<Equal<IsAny<never>, false>>,
Expect<Equal<IsAny<string>, false>>,
];This uses the Equal and Expect helpers from earlier. Here the checked type is the literal 0, not a type parameter, so no distribution occurs. 0 extends any is true. For unknown, the right side becomes 1, and 0 extends 1 is false. For never, the right side is never, and 0 extends never is false.
Guarding generic helpers
A helper that must treat the corners explicitly checks them first, from the most special case outward. Order matters because never and any would otherwise fall into a distributive branch.
type IsNever<T> = [T] extends [never] ? true : false;
type IsAny<T> = 0 extends 1 & T ? true : false;
type Kind<T> =
IsNever<T> extends true
? "never"
: IsAny<T> extends true
? "any"
: T extends string
? "text"
: "other";
type K1 = Kind<never>; // "never"
type K2 = Kind<any>; // "any"
type K3 = Kind<"a">; // "text"
type K4 = Kind<string | number>; // "text" | "other"IsNever<T> extends true is not distributive because the checked type is IsNever<T>, not a naked T. The final T extends string is distributive on purpose, so K4 reports both members.
Corners in mapped types
Mapped types have their own corner behavior. A homomorphic mapped type (one of the form { [K in keyof T]: ... } over a type parameter T) distributes over unions, so it also maps never to never. For any, the result is an object type with a string index signature, so Partial<any> is not any. Primitives pass through unchanged: Partial<string> is string. Arrays and tuples keep their shape, so Readonly<number[]> is readonly number[].
The keyof operator has corners too:
type K1 = keyof any; // string | number | symbol
type K2 = keyof never; // string | number | symbol
type K3 = keyof unknown; // neverkeyof unknown is never, because unknown has no known properties. Mapping over it yields {}. This matters when a filter such as PickByValue drops every key. The result is {}, not never, because the mapped type is still an object type with zero properties.
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
type Mixed = { id: number; name: string };
type Numbers = PickByValue<Mixed, number>; // { id: number }
type Booleans = PickByValue<Mixed, boolean>; // {}In the as clause, K is a single key at each step. The conditional there is not distributing over a union of keys, so the corner cases are about T[K]. If a property has type any, T[K] extends V yields K | never, which is K. An any property therefore always survives the filter.
Deferred conditionals inside generics
While T is still unknown, for example inside a generic function body, the compiler defers the conditional type. It cannot see which branch will be chosen, so it will not let you assign a value to it.
type Wrap<T> = T extends string ? { text: T } : { value: T };
function wrap<T>(input: T): Wrap<T> {
// return { value: input }; // error: not assignable to deferred Wrap<T>
return { value: input } as Wrap<T>;
}A cast is the usual remedy, because the compiler cannot prove the relationship. Keep the cast inside a small, well-tested function and give the function a precise public signature. Overloads are an alternative when the branches are few.
Common errors
- Using
T extends neverto detectnever. The result isnever, nottrue. - Expecting
Exclude<boolean, true>to returnboolean. It returnsfalse, becausebooleansplits intotrue | false. - Wrapping with
[T]and forgetting thatneverthen passes everyextendscheck. - Assuming
anytakes one branch. In the checked position it takes both. - Writing
T extends [U]and expecting distribution to stop. Only the checked side needs the wrapper.
Exercise
Given type ToArray<T> = T extends unknown ? T[] : never;, what is ToArray<never>? Write a version that returns never[] for never and (string | number)[] for string | number.
Show answer
ToArray<never> is never, because distribution over an empty union runs zero checks. The non-distributive version is type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;. For never it gives never[], and for string | number it gives (string | number)[].
Exercise
What do IsAny<any> and IsAny<unknown> return for type IsAny<T> = 0 extends 1 & T ? true : false;, and why do they differ?
Show answer
IsAny<any> is true and IsAny<unknown> is false. 1 & any is any, and 0 extends any is true. 1 & unknown is 1, and 0 is not assignable to 1. Since 0 is a literal and not a type parameter, the check does not distribute.
Exercise
A type Result<T> = T extends Error ? "failure" : "success" is applied to boolean. What is the result, and how would you make the answer a single value?
Show answer
boolean is true | false. Neither member extends Error, so each yields "success", and the union collapses to "success". If a union of different members were passed, you would get a union of results. To get one value for the whole type, use [T] extends [Error] ? "failure" : "success".