Advanced TypeScript utility types for building type-safe applications with complex type transformations
# TypeScript Utility Types for Google Antigravity
Master TypeScript utility types with Google Antigravity's Gemini 3 engine. This guide covers built-in utilities, custom type helpers, conditional types, and template literal types.
## Built-in Utility Types
```typescript
// Basic utility types
interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'user' | 'moderator';
createdAt: Date;
updatedAt: Date;
deletedAt?: Date;
}
// Partial - All properties optional
type PartialUser = Partial<User>;
// { id?: string; email?: string; ... }
// Required - All properties required
type RequiredUser = Required<User>;
// { id: string; ... deletedAt: Date; }
// Readonly - All properties readonly
type ReadonlyUser = Readonly<User>;
// { readonly id: string; readonly email: string; ... }
// Pick - Select specific properties
type UserPreview = Pick<User, 'id' | 'name' | 'email'>;
// { id: string; name: string; email: string; }
// Omit - Remove specific properties
type UserWithoutTimestamps = Omit<User, 'createdAt' | 'updatedAt' | 'deletedAt'>;
// { id: string; email: string; name: string; role: ... }
// Record - Create object type with specific keys
type RolePermissions = Record<User['role'], string[]>;
// { admin: string[]; user: string[]; moderator: string[]; }
// Exclude - Remove types from union
type NonAdminRole = Exclude<User['role'], 'admin'>;
// 'user' | 'moderator'
// Extract - Extract types from union
type AdminRole = Extract<User['role'], 'admin' | 'superadmin'>;
// 'admin'
// NonNullable - Remove null and undefined
type DefinitelyDate = NonNullable<User['deletedAt']>;
// Date
// ReturnType - Get function return type
function createUser(data: Omit<User, 'id'>) {
return { ...data, id: crypto.randomUUID() };
}
type CreatedUser = ReturnType<typeof createUser>;
// Parameters - Get function parameters
type CreateUserParams = Parameters<typeof createUser>;
// [data: Omit<User, 'id'>]
```
## Custom Utility Types
```typescript
// DeepPartial - Recursive partial
type DeepPartial<T> = T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
interface Config {
database: {
host: string;
port: number;
credentials: {
user: string;
password: string;
};
};
cache: {
enabled: boolean;
ttl: number;
};
}
type PartialConfig = DeepPartial<Config>;
// All nested properties are also optional
// DeepReadonly - Recursive readonly
type DeepReadonly<T> = T extends object
? { readonly [P in keyof T]: DeepReadonly<T[P]> }
: T;
// Mutable - Remove readonly
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
// RequireAtLeastOne - At least one property required
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
}[Keys];
interface SearchParams {
query?: string;
category?: string;
tag?: string;
}
type ValidSearchParams = RequireAtLeastOne<SearchParams>;
// Must have at least one of: query, category, or tag
// RequireOnlyOne - Exactly one property required
type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
> &
{
[K in Keys]-?: Required<Pick<T, K>> &
Partial<Record<Exclude<Keys, K>, never>>;
}[Keys];
// Nullable - Make properties nullable
type Nullable<T> = { [P in keyof T]: T[P] | null };
// NonNullableObject - Remove null from all properties
type NonNullableObject<T> = {
[P in keyof T]: NonNullable<T[P]>;
};
```
## Conditional Types
```typescript
// IsArray - Check if type is array
type IsArray<T> = T extends any[] ? true : false;
// UnwrapPromise - Get type from Promise
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
// ArrayElement - Get array element type
type ArrayElement<T> = T extends (infer U)[] ? U : never;
// FunctionReturnType with async handling
type AsyncReturnType<T extends (...args: any) => any> = T extends (
...args: any
) => Promise<infer R>
? R
: T extends (...args: any) => infer R
? R
: never;
// Filter object keys by value type
type KeysOfType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
interface Product {
id: string;
name: string;
price: number;
inStock: boolean;
tags: string[];
}
type StringKeys = KeysOfType<Product, string>;
// 'id' | 'name'
type NumberKeys = KeysOfType<Product, number>;
// 'price'
// Filter object to only include certain value types
type PickByType<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
type ProductStrings = PickByType<Product, string>;
// { id: string; name: string; }
```
## Template Literal Types
```typescript
// Event handler names
type EventName = 'click' | 'focus' | 'blur';
type EventHandler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'
// API routes
type HttpMethod = 'get' | 'post' | 'put' | 'delete';
type Resource = 'users' | 'products' | 'orders';
type ApiRoute = `/${Resource}` | `/${Resource}/:id`;
// '/users' | '/users/:id' | '/products' | ...
// CSS property values
type CSSUnit = 'px' | 'rem' | 'em' | '%';
type CSSValue = `${number}${CSSUnit}`;
// '10px', '1.5rem', etc.
// Type-safe object paths
type PathImpl<T, Key extends keyof T> = Key extends string
? T[Key] extends Record<string, any>
?
| `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}`
| `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}`
: never
: never;
type Path<T> = PathImpl<T, keyof T> | keyof T;
type UserPath = Path<User>;
// 'id' | 'email' | 'name' | 'role' | ...
// Get value type at path
type PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`
? Key extends keyof T
? PathValue<T[Key], Rest>
: never
: P extends keyof T
? T[P]
: never;
function getValue<T, P extends string>(obj: T, path: P): PathValue<T, P> {
return path.split('.').reduce((o: any, k) => o?.[k], obj);
}
```
## API Response Types
```typescript
// Generic API response wrapper
type ApiResponse<T> =
| { success: true; data: T }
| { success: false; error: { code: string; message: string } };
// Paginated response
interface PaginatedResponse<T> {
items: T[];
pagination: {
page: number;
limit: number;
total: number;
pages: number;
};
}
// Make API client type-safe
type ApiEndpoints = {
'/users': { GET: User[]; POST: User };
'/users/:id': { GET: User; PUT: User; DELETE: void };
'/products': { GET: PaginatedResponse<Product> };
};
type ApiClient = {
[Path in keyof ApiEndpoints]: {
[Method in keyof ApiEndpoints[Path]]: () => Promise<
ApiResponse<ApiEndpoints[Path][Method]>
>;
};
};
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these TypeScript patterns: Use utility types to avoid repetitive type definitions. Leverage conditional types for flexible type transformations. Implement template literal types for string-based type safety. Create project-specific utility types for common patterns. Document complex types with JSDoc comments.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.