Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
TypeScript Продвинутые Типы Руководство

TypeScript Продвинутые Типы Руководство

Освойте продвинутые типы TypeScript: дженерики, утилитарные типы, условные типы и защитники типов. Полное руководство по типобезопасной разработке.

typescriptтипыдженерикирусскийrussianпрограммирование
by AntigravityAI
⭐0Stars
👁️2Views
.antigravity
# TypeScript Продвинутые Типы Руководство

Освойте продвинутую систему типов TypeScript с Google Antigravity IDE. Это полное руководство охватывает дженерики, условные типы и паттерны типобезопасности.

## Почему продвинутые типы?

Продвинутые типы TypeScript обеспечивают безопасность на этапе компиляции. Google Antigravity IDE с Gemini 3 предоставляет интеллектуальные подсказки по типам.

## Основы дженериков

```typescript
// Базовая дженерик-функция
function identity<T>(value: T): T {
  return value;
}

// Дженерик с ограничениями
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Дженерик-класс
class Repository<T extends { id: string }> {
  private items: Map<string, T> = new Map();
  
  add(item: T): void {
    this.items.set(item.id, item);
  }
  
  get(id: string): T | undefined {
    return this.items.get(id);
  }
  
  getAll(): T[] {
    return Array.from(this.items.values());
  }
  
  filter<K extends keyof T>(key: K, value: T[K]): T[] {
    return this.getAll().filter((item) => item[key] === value);
  }
}

// Использование
interface User {
  id: string;
  name: string;
  role: "admin" | "user";
}

const userRepo = new Repository<User>();
userRepo.add({ id: "1", name: "Иван", role: "admin" });
const admins = userRepo.filter("role", "admin");
```

## Условные типы

```typescript
// Базовый условный тип
type IsString<T> = T extends string ? true : false;

// Ключевое слово infer для извлечения типов
type ReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;

type ArrayElement<T> = T extends (infer E)[] ? E : never;

type PromiseValue<T> = T extends Promise<infer V> ? V : T;

// Дистрибутивные условные типы
type NonNullable<T> = T extends null | undefined ? never : T;

// Практический пример: обработка API ответов
type ApiResponse<T> = T extends { error: infer E }
  ? { success: false; error: E }
  : { success: true; data: T };

type UnwrapPromise<T> = T extends Promise<infer U>
  ? U extends Promise<infer V>
    ? UnwrapPromise<V>
    : U
  : T;

// Глубокий readonly
type DeepReadonly<T> = T extends object
  ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
  : T;
```

## Mapped типы

```typescript
// Базовый mapped тип
type Optional<T> = {
  [K in keyof T]?: T[K];
};

// Readonly с условиями
type ReadonlyExcept<T, K extends keyof T> = {
  readonly [P in Exclude<keyof T, K>]: T[P];
} & {
  [P in K]: T[P];
};

// Mapped тип с переименованием ключей
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type Setters<T> = {
  [K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};

// Обработчики событий
type EventHandlers<T> = {
  [K in keyof T as `on${Capitalize<string & K>}Change`]: (
    newValue: T[K],
    oldValue: T[K]
  ) => void;
};

interface User {
  name: string;
  age: number;
}

type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; }
```

## Template Literal типы

```typescript
// Извлечение параметров маршрута
type ExtractParams<T extends string> =
  T extends `${string}:${infer Param}/${infer Rest}`
    ? Param | ExtractParams<Rest>
    : T extends `${string}:${infer Param}`
    ? Param
    : never;

type RouteParams = ExtractParams<"/users/:userId/posts/:postId">;
// "userId" | "postId"

// Типобезопасный эмиттер событий
type EventName<T extends string> = `${T}:${string}`;

type ParseEvent<T> = T extends `${infer Category}:${infer Name}`
  ? { category: Category; name: Name }
  : never;
```

## Утилитарные паттерны типов

```typescript
// Deep partial
type DeepPartial<T> = T extends object
  ? { [K in keyof T]?: DeepPartial<T[K]> }
  : T;

// Выбор по типу значения
type PickByType<T, V> = {
  [K in keyof T as T[K] extends V ? K : never]: T[K];
};

// Исключение по типу значения
type OmitByType<T, V> = {
  [K in keyof T as T[K] extends V ? never : K]: T[K];
};

// Только обязательные ключи
type RequiredKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];

// Слияние двух типов
type Merge<T, U> = Omit<T, keyof U> & U;
```

## Type Guards

```typescript
// Пользовательский type guard
function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value
  );
}

// Discriminated union guard
type Result<T, E = Error> =
  | { success: true; data: T }
  | { success: false; error: E };

function isSuccess<T, E>(result: Result<T, E>): result is { success: true; data: T } {
  return result.success === true;
}

// Assertion функция
function assertDefined<T>(value: T | undefined): asserts value is T {
  if (value === undefined) {
    throw new Error("Значение не определено");
  }
}
```

## Лучшие практики

- Используйте дженерики для переиспользуемого типобезопасного кода
- Применяйте условные типы для трансформации типов
- Используйте mapped типы для манипуляции объектами
- Создавайте type guards для проверки во время выполнения
- Документируйте сложные типы с помощью JSDoc

Google Antigravity IDE обеспечивает интеллектуальный вывод типов и предлагает продвинутые паттерны для вашего TypeScript кода.

When to Use This Prompt

This typescript prompt is ideal for developers working on:

  • typescript applications requiring modern best practices and optimal performance
  • Projects that need production-ready typescript code with proper error handling
  • Teams looking to standardize their typescript development workflow
  • Developers wanting to learn industry-standard typescript patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the typescript code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this typescript prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...