Master TypeScript generics and type manipulation in Google Antigravity for safer and more expressive code patterns
# 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 codebaseThis 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.