PassFront
  1. PassFront
  2. База знаний
  3. Типы и интерфейсы

Как описать объект в TypeScript?

Типы и интерфейсы

Объект в TypeScript описывают через `interface`, `type` или встроенные типы вроде `Record`.

interface и type

interface User {
  readonly id: string;
  name: string;
  email?: string;              // необязательное поле
  tags: string[];
  address: { city: string };   // вложенный объект
}

type Point = { x: number; y: number };

Словари

type Scores = Record<string, number>;
interface Translations { [key: string]: string }

Типы на основе других

type UserPreview = Pick<User, 'id' | 'name'>;
type UserUpdate = Partial<Omit<User, 'id'>>;

Тип из значения

const defaults = { theme: 'light', pageSize: 20 } as const;
type Defaults = typeof defaults;

Проверка без потери точности

const config = { port: 3000 } satisfies Record<string, number>;

Коротко для собеседования

Через interface или type с полями (необязательные ?, readonly), Record для словарей, утилиты Pick/Omit/Partial и typeof для вывода типа из значения.

Подробнее: TypeScript Handbook — Object Types

Другие вопросы раздела