Sub topic 12
Edge cases: never, any, and non-distributive checks
This chapter assumes you can write conditional types with extends, understand what a naked type parameter is, and have used infer at least once. You should also be comfortable with union types.
Three kinds of input cause most surprises in conditional types: never, any, and unions. Each one changes what a conditional type returns, and each one has a known fix.
Distribution over unions
When a conditional type checks a naked type parameter (a plain T with nothing wrapped around it), TypeScript applies the check to each union member separately and joins the results.
type ToArray<T> = T extends unknown ? T[] : never;
type D = ToArray<string | number>; // string[] | number[]Wrapping the parameter in a tuple turns distribution off, so the check runs once on the whole union.
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type N = ToArrayNonDist<string | number>; // (string | number)[]Use the plain form when each member should get its own answer. Use the tuple form when the union should be treated as one unit.
never
never is the type with no values. A distributive conditional type applied to never produces never, because distributing over an empty union leaves nothing to compute.
type IsString<T> = T extends string ? true : false;
type A = IsString<never>; // neverMany readers expect false here. To ask whether a type is never, wrap both sides in a tuple so the check does not distribute:
type IsNever<T> = [T] extends [never] ? true : false;
type B = IsNever<never>; // true
type C = IsNever<string>; // falseA filter can also produce never by accident. If every member of a union is removed by the check, the result is never. That is the correct result for an empty set of members.
any
When the checked type is any, TypeScript cannot choose one branch, so the result is the union of both branches.
type Label<T> = T extends string ? "text" : "other";
type E = Label<any>; // "text" | "other"To detect any directly, use a check that only any satisfies:
type IsAny<T> = 0 extends 1 & T ? true : false;
type F = IsAny<any>; // true
type G = IsAny<string>; // falseChecking a whole union
Sometimes you want to ask a question about the union as a whole, such as whether every member is a string.
type AllStrings<T> = [T] extends [string] ? true : false;
type H = AllStrings<"a" | "b">; // true
type I = AllStrings<"a" | 1>; // falseExercise
Exercise
Given type Label<T> = T extends string ? "text" : "other";, what does Label<never> produce, and why?
Show answer
It produces never. The check distributes over the empty union that never represents. No member is checked, so no branch is chosen and the result is never.