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
Advanced TypeScript Types & Generics

Advanced TypeScript Types & Generics

Master advanced TypeScript features including utility types, conditional types, mapped types, and type inference.

TypeScriptTypesGenericsAdvanced
by Community
⭐0Stars
👁️12Views
📋1Copies
.antigravity
# Advanced TypeScript Types & Generics

Master advanced TypeScript type system with Google Antigravity IDE. This comprehensive guide covers generics, conditional types, mapped types, and utility patterns for type-safe applications.

## Why Advanced Types?

TypeScript's advanced type system enables compile-time safety for complex patterns. Google Antigravity IDE's Gemini 3 engine provides intelligent type inference and suggests type improvements.

## Generic Fundamentals

```typescript
// Basic generic function
function identity<T>(value: T): T {
  return value;
}

// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Generic class
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);
  }
}

// Usage
interface User {
  id: string;
  name: string;
  role: "admin" | "user";
}

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

## Conditional Types

```typescript
// Basic conditional type
type IsString<T> = T extends string ? true : false;

// Infer keyword for type extraction
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;

// Distributive conditional types
type NonNullable<T> = T extends null | undefined ? never : T;

// Practical example: API response handling
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;

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

## Mapped Types

```typescript
// Basic mapped type
type Optional<T> = {
  [K in keyof T]?: T[K];
};

// Readonly with conditions
type ReadonlyExcept<T, K extends keyof T> = {
  readonly [P in Exclude<keyof T, K>]: T[P];
} & {
  [P in K]: T[P];
};

// Mapped type with key remapping
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;
};

// Event handlers
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; }

type UserEvents = EventHandlers<User>;
// { onNameChange: (newValue: string, oldValue: string) => void; ... }
```

## Template Literal Types

```typescript
// Route parameter extraction
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-safe event emitter
type EventName<T extends string> = `${T}:${string}`;

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

// CSS property types
type CSSProperty = `--${string}`;
type CSSValue = `${number}${"px" | "em" | "rem" | "%"}`;
```

## Utility Type Patterns

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

// Pick by value type
type PickByType<T, V> = {
  [K in keyof T as T[K] extends V ? K : never]: T[K];
};

// Omit by value type
type OmitByType<T, V> = {
  [K in keyof T as T[K] extends V ? never : K]: T[K];
};

// Required keys only
type RequiredKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];

// Optional keys only
type OptionalKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? K : never;
}[keyof T];

// Merge two types
type Merge<T, U> = Omit<T, keyof U> & U;

// Strict object type (no extra properties)
type Strict<T> = T & { [K in Exclude<string, keyof T>]?: never };
```

## Type Guards

```typescript
// Custom type guard
function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value &&
    typeof (value as User).id === "string"
  );
}

// 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
function assertDefined<T>(value: T | undefined, message?: string): asserts value is T {
  if (value === undefined) {
    throw new Error(message ?? "Value is undefined");
  }
}
```

## Best Practices

- Use generics for reusable type-safe code
- Apply conditional types for type transformations
- Leverage mapped types for object manipulation
- Use template literals for string patterns
- Create type guards for runtime validation
- Document complex types with JSDoc

Google Antigravity IDE provides intelligent type inference and suggests advanced type patterns for your TypeScript code.

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...