Master advanced TypeScript features including utility types, conditional types, mapped types, and type inference.
# 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.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.