Урок 10

Utility types

TypeScript предоставляет встроенные утилиты для преобразования типов.

Partial

Все поля опциональны:

type User = { name: string; age: number };
type PartialUser = Partial<User>;
// { name?: string; age?: number }

Используется для обновлений:

function update(id: number, patch: Partial<User>) {}
update(1, { name: 'Новое' });

Required

Все поля обязательны:

type User = { name?: string; age?: number };
type RequiredUser = Required<User>;
// { name: string; age: number }

Readonly

Все поля только для чтения:

type ReadonlyUser = Readonly<User>;

Pick

Выбрать определённые поля:

type UserPreview = Pick<User, 'id' | 'name'>;
// { id: number; name: string }

Omit

Исключить поля:

type SafeUser = Omit<User, 'password'>;

Record

Словарь:

type Scores = Record<string, number>;
type Roles = Record<'admin' | 'user', string>;

Exclude

Убрать из union:

type T = Exclude<'a' | 'b' | 'c', 'a'>;
// 'b' | 'c'

Extract

Оставить в union:

type T = Extract<'a' | 'b' | 'c', 'a' | 'b'>;
// 'a' | 'b'

NonNullable

Убрать null и undefined:

type T = NonNullable<string | null | undefined>;
// string

ReturnType

Тип возврата функции:

function getUser() {
    return { name: 'Алиса', age: 25 };
}

type User = ReturnType<typeof getUser>;
// { name: string; age: number }

Parameters

Типы параметров функции:

function add(a: number, b: number) {}

type Params = Parameters<typeof add>;
// [number, number]

Awaited

Тип после await:

type T = Awaited<Promise<string>>; // string

InstanceType

Тип экземпляра класса:

class User {}
type UserInstance = InstanceType<typeof User>;

Комбинирование

type UpdateUser = Partial<Omit<User, 'id' | 'createdAt'>>;

Кастомные утилиты

Свои утилиты через mapped types:

type Nullable<T> = { [K in keyof T]: T[K] | null };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

Итоги

  • Partial, Required, Readonly
  • Pick, Omit, Record
  • Exclude, Extract, NonNullable
  • ReturnType, Parameters, Awaited
  • Комбинируй для сложных типов
  • Кастомные через mapped types