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 FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 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 Advanced Generic Patterns

TypeScript Advanced Generic Patterns

Master TypeScript generics and type manipulation in Google Antigravity for safer and more expressive code patterns

TypeScriptGenericsType SafetyAdvanced TypesProgramming
by Antigravity Team
⭐0Stars
.antigravity
# TypeScript Advanced Generic Patterns for Google Antigravity

Advanced TypeScript generics enable expressive, type-safe code that catches errors at compile time. This guide establishes generic type patterns for Google Antigravity projects, enabling Gemini 3 to generate sophisticated type-level programming.

## Generic Function Patterns

Create flexible, type-safe functions:

```typescript
// Generic identity with constraints
function identity<T>(value: T): T {
  return value;
}

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

// Generic with default type
function createState<T = string>(initial: T): [T, (value: T) => void] {
  let state = initial;
  const setState = (value: T) => {
    state = value;
  };
  return [state, setState];
}

// Multiple type parameters with relationship
function merge<T extends object, U extends object>(a: T, b: U): T & U {
  return { ...a, ...b };
}

// Conditional return type based on input
function processValue<T extends string | number>(
  value: T
): T extends string ? string[] : number[] {
  if (typeof value === "string") {
    return value.split("") as T extends string ? string[] : number[];
  }
  return [value] as T extends string ? string[] : number[];
}
```

## Generic Class Patterns

Build type-safe data structures:

```typescript
// Generic repository pattern
interface Entity {
  id: string;
}

class Repository<T extends Entity> {
  private items: Map<string, T> = new Map();

  create(item: T): T {
    this.items.set(item.id, item);
    return item;
  }

  findById(id: string): T | undefined {
    return this.items.get(id);
  }

  findAll(): T[] {
    return Array.from(this.items.values());
  }

  findWhere<K extends keyof T>(key: K, value: T[K]): T[] {
    return this.findAll().filter((item) => item[key] === value);
  }

  update(id: string, updates: Partial<Omit<T, "id">>): T | undefined {
    const item = this.items.get(id);
    if (!item) return undefined;
    const updated = { ...item, ...updates };
    this.items.set(id, updated);
    return updated;
  }

  delete(id: string): boolean {
    return this.items.delete(id);
  }
}

// Usage with specific entity
interface User extends Entity {
  name: string;
  email: string;
  role: "admin" | "user";
}

const userRepo = new Repository<User>();
userRepo.create({ id: "1", name: "John", email: "john@example.com", role: "admin" });
const admins = userRepo.findWhere("role", "admin");
```

## Generic Utility Types

Create reusable type utilities:

```typescript
// Deep Partial - recursively make all properties optional
type DeepPartial<T> = T extends object
  ? { [P in keyof T]?: DeepPartial<T[P]> }
  : T;

// Deep Required - recursively make all properties required
type DeepRequired<T> = T extends object
  ? { [P in keyof T]-?: DeepRequired<T[P]> }
  : T;

// Deep Readonly - recursively make all properties readonly
type DeepReadonly<T> = T extends object
  ? { readonly [P in keyof T]: DeepReadonly<T[P]> }
  : T;

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

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

// Get keys that are functions
type FunctionKeys<T> = {
  [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? K : never;
}[keyof T];

// Make specific keys optional
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

// Make specific keys required
type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;

// Example usage
interface Config {
  apiUrl: string;
  timeout: number;
  features: {
    darkMode: boolean;
    analytics: boolean;
  };
  onError: (error: Error) => void;
}

type DeepPartialConfig = DeepPartial<Config>;
type StringConfig = PickByValue<Config, string>; // { apiUrl: string }
type ConfigFunctions = FunctionKeys<Config>; // "onError"
```

## Conditional Types

Implement type-level logic:

```typescript
// Extract array element type
type ArrayElement<T> = T extends readonly (infer E)[] ? E : never;
type Numbers = ArrayElement<number[]>; // number

// Extract Promise resolved type
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type Resolved = UnwrapPromise<Promise<string>>; // string

// Recursive flatten
type Flatten<T> = T extends (infer U)[] ? Flatten<U> : T;
type Flat = Flatten<number[][][]>; // number

// Exclude null and undefined
type NonNullableDeep<T> = T extends object
  ? { [K in keyof T]: NonNullableDeep<NonNullable<T[K]>> }
  : NonNullable<T>;

// Filter object properties by value type
type FilterByValue<T, V> = {
  [K in keyof T as T[K] extends V ? K : never]: T[K];
};

interface Mixed {
  name: string;
  age: number;
  active: boolean;
  score: number;
}

type NumberProps = FilterByValue<Mixed, number>;
// { age: number; score: number }
```

## Template Literal Types

Build string-based type utilities:

```typescript
// Event name builder
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"

// Route path builder
type ApiRoute<T extends string> = `/api/${T}`;
type UsersRoute = ApiRoute<"users">; // "/api/users"

// Extract route params
type ExtractParams<T extends string> =
  T extends `${infer _Start}:${infer Param}/${infer Rest}`
    ? Param | ExtractParams<`/${Rest}`>
    : T extends `${infer _Start}:${infer Param}`
    ? Param
    : never;

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

// Build typed route handler
type RouteParams<T extends string> = {
  [K in ExtractParams<T>]: string;
};

type UserPostParams = RouteParams<"/users/:userId/posts/:postId">;
// { userId: string; postId: string }

// CSS property builder
type CSSVar<T extends string> = `--${T}`;
type ThemeVar = CSSVar<"primary-color">; // "--primary-color"
```

## Best Practices

1. **Start simple**: Use built-in utilities before custom types
2. **Document complex types**: Add JSDoc comments
3. **Test types**: Use type assertions to verify
4. **Avoid over-engineering**: Keep types readable
5. **Extract reusable types**: Share across codebase

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