Sub topic 12
How never behaves in unions, intersections, and conditional types
Earlier chapters showed never as the return type of functions that don't finish and as the type of the leftover value in an exhaustive switch. This chapter covers what the compiler does when never appears inside other types. Most of the time it silently disappears, sometimes it swallows the whole type, and in conditional types it can produce surprising results.
This chapter assumes you know union and intersection types, generics with extends constraints, and the basics of conditional types (T extends U ? X : Y). The examples need TypeScript 4.1 or later, because they use key remapping with as.
Why never behaves this way
Think of types as sets of values, as in the first chapter. never is the empty set. Two facts from set theory explain nearly everything below:
- Joining a set with the empty set changes nothing. This is union.
- Overlapping any set with the empty set leaves the empty set. This is intersection.
A conditional type applied to each member of a union is a mapping over a set. Mapping over zero members gives zero results.
never in unions: the identity element
Adding never to a union has no effect. The compiler removes it during normalization.
type A = string | never; // string
type B = never | never; // never
type C = "x" | "y" | never; // "x" | "y"
function maybeFail(ok: boolean): string | never {
if (!ok) throw new Error("failed");
return "fine";
}
const result = maybeFail(true); // type: stringThe return type string | never is the same as string. Writing | never documents intent only, and the compiler does not enforce it.
This behavior is what makes never useful as a way to delete members. If a conditional type returns never for a union member, that member vanishes from the result. The mapped-type examples later in this chapter depend on it.
A related use is a property typed never, which forbids a value in one variant of a union:
type Circle = { radius: number; size?: never };
type Square = { size: number; radius?: never };
type Shape = Circle | Square;
const ok: Shape = { radius: 2 };
// const bad: Shape = { radius: 2, size: 3 }; // error: no member accepts bothAn optional property of type never still accepts undefined, so { radius: 2, size: undefined } compiles unless you enable exactOptionalPropertyTypes.
never in intersections: the absorbing element
Intersecting any type with never gives never. Intersecting two types that share no values also gives never.
type D = string & never; // never
type E = string & number; // never
type F = { kind: "a" } & { kind: "b" }; // neverThe third case needs explanation. The compiler reduces an intersection of object types to never when a property with the same name has non-overlapping literal (unit) types in each member. This reduction was added in TypeScript 3.9. Without it, F would be an object type with kind: never, which no value could satisfy.
The reduction applies only to discriminant-like properties, meaning literal types, null, and undefined. These do not reduce:
type G = { id: string } & { id: number };
// Not reduced to never. The type still exists, but its id property is string & number, which is never.
// Any object value you try to create for it is rejected.Because G is not collapsed, the error appears later, when you build a value. If you intersect object types from different sources, check the resulting type by hovering over it in your editor.
| Expression | Result | Reason | Column |
|---|---|---|---|
| `T \ | never` | `T` | `never` contributes no values to a union |
| `T & never` | `never` | No value is both a `T` and nothing | |
| `string & number` | `never` | The two sets do not overlap | |
| `{ kind: "a" } & { kind: "b" }` | `never` | Discriminant reduction (TypeScript 3.9 and later) | |
| `{ id: string } & { id: number }` | Not reduced | Only the `id` property is `never` |
never in conditional types: distribution
A conditional type distributes over a union when the checked type is a naked type parameter, meaning the parameter appears alone to the left of extends. The compiler applies the condition to each union member and unions the results.
type Without<T, U> = T extends U ? never : T;
type R = Without<"a" | "b" | "c", "a">; // "b" | "c"The evaluation steps for R:
The built-in Exclude<T, U> is exactly this type, and Extract<T, U> is the same type with T and never swapped. Use the built-ins unless you need a variation.
Disabling distribution
Wrapping both sides in a one-element tuple turns off distribution, because [T] is no longer a naked type parameter:
type NoDist<T, U> = [T] extends [U] ? never : T;
type X = NoDist<"a" | "b", "a">; // "a" | "b"Here the whole union "a" | "b" is tested once against "a". The test fails, so the result is T.
The empty union trap
Distribution over never visits zero members, so the result is never. It does not take either branch:
type BadIsNever<T> = T extends never ? true : false;
type T1 = BadIsNever<never>; // never, not true
type T2 = BadIsNever<string>; // falseThe correct test avoids distribution:
type IsNever<T> = [T] extends [never] ? true : false;
type T3 = IsNever<never>; // true
type T4 = IsNever<string>; // false
type T5 = IsNever<string | never>; // false (this is just string)Using never to filter keys
Conditional types plus never give you two common filtering patterns for object types.
The first pattern builds a union of keys whose value type matches. Properties mapped to never disappear when you index the mapped type with keyof T:
interface Config {
host: string;
port: number;
debug: boolean;
name: string;
}
type KeysOfType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];
type StringKeys = KeysOfType<Config, string>; // "host" | "name"The -? modifier removes the undefined that optional properties would otherwise add to the result. A property whose type includes undefined, such as a?: string, still won't match string, because string | undefined doesn't extend string.
The second pattern uses key remapping (as) to drop properties during the mapping. A key remapped to never is removed from the resulting object type:
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type StringProps = OnlyStrings<Config>;
// { host: string; name: string }Prefer the second pattern when you want an object type. Use the first when you need the key names themselves.
Assignability rules to remember
neveris assignable to every type, so anevervalue can be used anywhere. This is whyreturn fail("...")type-checks in a function returningstring.- Nothing except
neveris assignable tonever. Assigning evenanyto anevervariable is an error. - A function type returning
neveris assignable to a function type returning anything, sinceneveris a subtype of every type.
Debugging checklist
When a type resolves to never and you didn't expect it, check these causes in order:
- An intersection of types with conflicting literal properties, such as two different
kindvalues. - A conditional type that distributed over an empty union.
- An
ExcludeorExtractthat removed every member becauseUwas broader than you intended. - A mapped type or indexed access on a key that doesn't exist in any member of a union.
Hover over each intermediate type alias in your editor. Splitting a long type into named steps shows where the never first appears.
Exercise
What are the types of A, B, and C below?
type Pick1<T, U> = T extends U ? T : never;
type A = Pick1<string | number | boolean, string | boolean>;
type B = Pick1<never, string>;
type C = [never] extends [string] ? "yes" : "no";
Show answer
A is string | boolean. The condition distributes over each member: string and boolean extend string | boolean and are kept, while number maps to never and disappears. B is never, because distribution over the empty union visits no members. C is "yes", because the tuple wrapper disables distribution and never is assignable to string.
Exercise
Write a type NonNeverKeys<T> that returns the union of keys of T whose property type is not never. For { a: string; b: never; c: number } it should give "a" | "c".
Show answer
type NonNeverKeys<T> = { [K in keyof T]-?: [T[K]] extends [never] ? never : K }[keyof T]; The tuple wrapper is required. Without it, T[K] extends never would still work for a concrete property type, but the wrapper keeps the check correct if T[K] is itself a union or never resolved through a generic. Keys whose value is never map to never and drop out of the final union, leaving "a" | "c".