Освойте продвинутые типы TypeScript: дженерики, утилитарные типы, условные типы и защитники типов. Полное руководство по типобезопасной разработке.
# TypeScript Продвинутые Типы
Изучите продвинутые концепции TypeScript для создания надёжных и типобезопасных приложений.
## Дженерики (Обобщённые Типы)
```typescript
// Обобщённая функция
function firstElement<T>(array: T[]): T | undefined {
return array[0];
}
const numbers = firstElement([1, 2, 3]); // тип: number
const strings = firstElement(["a", "b"]); // тип: string
// Обобщённый интерфейс
interface ApiResponse<T> {
data: T;
success: boolean;
message?: string;
timestamp: Date;
}
interface User {
id: string;
name: string;
email: string;
}
async function getUser(id: string): Promise<ApiResponse<User>> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
```
## Утилитарные Типы
```typescript
interface Product {
id: string;
name: string;
price: number;
description: string;
stock: number;
createdAt: Date;
}
// Partial - все свойства опциональны
type ProductUpdate = Partial<Product>;
// Pick - только определённые свойства
type ProductPreview = Pick<Product, "id" | "name" | "price">;
// Omit - исключить определённые свойства
type NewProduct = Omit<Product, "id" | "createdAt">;
// Required - все свойства обязательны
type CompleteProduct = Required<Product>;
// Readonly - все свойства только для чтения
type ImmutableProduct = Readonly<Product>;
```
## Условные Типы
```typescript
// Простой условный тип
type IsString<T> = T extends string ? true : false;
type Test1 = IsString<string>; // true
type Test2 = IsString<number>; // false
// Извлечение типа элемента массива
type ArrayElement<T> = T extends (infer E)[] ? E : never;
type NumberElement = ArrayElement<number[]>; // number
```
## Защитники Типов
```typescript
interface Dog {
type: "dog";
bark: () => void;
}
interface Cat {
type: "cat";
meow: () => void;
}
type Pet = Dog | Cat;
// Функция-защитник типа
function isDog(pet: Pet): pet is Dog {
return pet.type === "dog";
}
function petSound(pet: Pet) {
if (isDog(pet)) {
pet.bark(); // TypeScript знает, что pet это Dog
} else {
pet.meow(); // TypeScript знает, что pet это Cat
}
}
```
Это руководство поможет русскоязычным разработчикам полностью понять систему типов TypeScript.This typescript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their typescript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For typescript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.