TS - сопоставимые типы

Exclude Link to heading

Exclude<UnionType, ExcludedMembers> - исключает определенные типы из объединенного типа:

type A = 'a' | 'b' | 'c'
type B = Exclude<A, 'a' | 'b'>
// -> B = 'c'
type Shape =
  { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };

type T3 = Exclude<Shape, { kind: "circle" }>

type T3 =
  { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number }

Extract Link to heading

Extract<Type, Union> - извлекает из типа только те, которые присутствуют в обоих объединенных типах:

type A = 'a' | 'b' | 'c';
type B = 'a' | 'b';

type C = Extract<A, B>;
// -> C = 'a' | 'b'
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };

type T2 = Extract<Shape, { kind: "circle" }>

type T2 = {
    kind: "circle";
    radius: number;
}

NonNullable Link to heading

NonNullable<Type> - извлекает все типы, исключая null и undefined:

let value: string | null | undefined;
let nonNullableValue: NonNullable<typeof value>;
// теперь nonNullableValue это string