Sub topic 3
Conflicting Members and Intersections That Become `never`
Assume you know TypeScript type aliases, object types, and function annotations. This chapter focuses on how intersections behave when their requirements conflict.
Conflicting members and `never`
An intersection (&) requires a value to satisfy every combined type. If two types require incompatible values, the result can become never. never is the type of values that cannot exist.
type Impossible = string & number;
declare const value: Impossible;
const n: never = value;An object intersection can remain partly usable while one property becomes never:
type HasId = { id: string };
type NumericId = { id: number };
type Broken = HasId & NumericId;
// { id: never }No value can provide an id that is both a string and a number.
Intersections or `interface extends`
Use an intersection when composing existing types locally:
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;An interface can extend another interface when you are defining an intended, reusable shape:
interface ArticleView extends Named {
createdAt: Date;
}extends reports incompatible inherited properties as an error during the declaration. An intersection may instead produce a type with a conflicting property that is effectively never. Prefer extends when you want early, explicit validation and declaration merging. Prefer intersections for flexible type composition.
How intersections distribute over unions
An intersection applied to a union usually behaves like an intersection with each alternative:
type A = { a: string };
type B = { b: number };
type C = { c: boolean };
type Result = A & (B | C);
// (A & B) | (A & C)A value must have A, plus either B or C.
Distributive conditional types
A conditional type distributes when a naked type parameter appears on the left of extends:
type ToArray<T> = T extends unknown ? T[] : never;
type Separate = ToArray<string | number>; // string[] | number[]Wrap the type parameter in a tuple to keep the union together:
type OneArray<T> = [T] extends [unknown] ? T[] : never;
type Combined = OneArray<string | number>; // (string | number)[]Unions and intersections of function types
A union of functions can usually be called only with an argument accepted by every member. An intersection behaves more like overloads:
type Convert =
((x: string) => number) &
((x: number) => string);
declare const convert: Convert;
const a = convert("42"); // number
const b = convert(42); // stringExercise
What is the practical difference between string | number and string & number?
Show answer
A union allows either type, while the intersection requires both. Since no value is both a string and a number, string & number becomes never.