← Назад к вопросам
Что в TypeScript позволяет использовать объект как тип?
2.0 Middle🔥 172 комментариев
#TypeScript
Комментарии (2)
🐱
claude-haiku-4.5PrepBro AI3 апр. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
typeof оператор
В TypeScript существует специальный оператор typeof, который позволяет использовать объект как тип. Это один из самых мощных инструментов для создания типов на основе существующих значений.
Извлечение типа из значения
// Объект как значение
const user = {
id: 1,
name: "Alice",
email: "alice@example.com",
role: "admin"
};
// Извлекаем тип из объекта
type User = typeof user;
// Эквивалентно:
// type User = {
// id: number;
// name: string;
// email: string;
// role: string;
// }
const newUser: User = {
id: 2,
name: "Bob",
email: "bob@example.com",
role: "user"
};
Извлечение типа из массива
// Массив объектов
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
type User = typeof users[0];
// type User = { id: number; name: string; }
// Или извлечём тип всего массива
type Users = typeof users;
// type Users = { id: number; name: string; }[]
typeof с функциями
// Функция как значение
const calculateTotal = (prices: number[]): number => {
return prices.reduce((sum, p) => sum + p, 0);
};
// Извлекаем тип функции
type CalculateTotal = typeof calculateTotal;
// type CalculateTotal = (prices: number[]) => number
// Используем как тип для другой функции
const myCalculate: CalculateTotal = (prices) => prices.length;
// ошибка: Type 'number' is not assignable to type 'number[]'
typeof с const объектами
Для более строгой типизации используем as const:
// Без as const - широкий тип
const colors = {
primary: "#3498db",
secondary: "#2ecc71"
};
type Colors1 = typeof colors;
// type Colors1 = { primary: string; secondary: string; }
// С as const - узкий тип (литеральные значения)
const colors2 = {
primary: "#3498db",
secondary: "#2ecc71"
} as const;
type Colors2 = typeof colors2;
// type Colors2 = {
// readonly primary: "#3498db";
// readonly secondary: "#2ecc71";
// }
keyof для извлечения ключей
После получения типа от объекта можно извлечь его ключи:
const settings = {
theme: "dark",
language: "en",
notifications: true
};
type Settings = typeof settings;
type SettingKeys = keyof Settings;
// type SettingKeys = "theme" | "language" | "notifications"
// Используем для типизации функций
function getSetting(key: SettingKeys): string | boolean {
return settings[key];
}
getSetting("theme"); // OK
getSetting("invalid"); // Ошибка: Argument of type '"invalid"' is not assignable
typeof в React компонентах
// API ответ как объект
const apiResponse = {
status: 200,
data: { id: 1, name: "Test" },
message: "Success"
};
type ApiResponse = typeof apiResponse;
// Используем в React
interface ComponentProps {
response: ApiResponse;
}
export function DataComponent({ response }: ComponentProps) {
return <div>{response.data.name}</div>;
}
typeof с классами
class User {
constructor(public id: number, public name: string) {}
getName() {
return this.name;
}
}
// Извлекаем тип экземпляра класса
type UserInstance = typeof new User(1, "Alice");
// Или проще:
type UserInstance = InstanceType<typeof User>;
// Но обычно просто используем класс как тип
const user: User = new User(1, "Alice");
Практический пример
// Конфигурация приложения
const config = {
api: {
baseUrl: "https://api.example.com",
timeout: 5000
},
features: {
darkMode: true,
analytics: false
}
} as const;
type Config = typeof config;
// Функция для работы с конфигом
function initApp(appConfig: Config) {
console.log(appConfig.api.baseUrl);
console.log(appConfig.features.darkMode);
}
initApp(config);
Оператор typeof позволяет создавать типы на основе существующих значений, что делает код более DRY и автоматически синхронизирует типы с реальными данными.