Master advanced TypeScript utility types for Google Antigravity applications including conditional types, mapped types, and template literals.
# Advanced TypeScript Type Patterns
Master advanced TypeScript utility types in your Google Antigravity applications. This guide covers built-in utilities, custom type helpers, and real-world patterns for type-safe code.
## Built-in Utility Types
Leverage TypeScript's built-in utilities:
```typescript
// Partial - Make all properties optional
interface Prompt {
id: string;
title: string;
content: string;
tags: string[];
}
type PromptUpdate = Partial<Prompt>;
// { id?: string; title?: string; content?: string; tags?: string[] }
// Required - Make all properties required
interface Config {
apiUrl?: string;
timeout?: number;
}
type RequiredConfig = Required<Config>;
// { apiUrl: string; timeout: number }
// Pick - Select specific properties
type PromptPreview = Pick<Prompt, "id" | "title">;
// { id: string; title: string }
// Omit - Exclude specific properties
type PromptWithoutId = Omit<Prompt, "id">;
// { title: string; content: string; tags: string[] }
// Record - Create object type with specific keys
type StatusMap = Record<"pending" | "approved" | "rejected", number>;
// { pending: number; approved: number; rejected: number }
// Exclude/Extract - Filter union types
type Status = "pending" | "approved" | "rejected" | null;
type NonNullStatus = Exclude<Status, null>;
// "pending" | "approved" | "rejected"
```
## Custom Utility Types
Create reusable type utilities:
```typescript
// lib/types/utilities.ts
// DeepPartial - Recursive partial
type DeepPartial<T> = T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
// DeepReadonly - Recursive readonly
type DeepReadonly<T> = T extends object
? { readonly [P in keyof T]: DeepReadonly<T[P]> }
: T;
// Nullable - Add null to type
type Nullable<T> = T | null;
// NonNullableFields - Remove null/undefined from all fields
type NonNullableFields<T> = {
[P in keyof T]: NonNullable<T[P]>;
};
// RequireAtLeastOne - Require at least one property
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];
// Example usage
interface SearchParams {
query?: string;
category?: string;
author?: string;
}
type ValidSearchParams = RequireAtLeastOne<SearchParams>;
```
## Conditional Types
Implement conditional type logic:
```typescript
// lib/types/conditional.ts
// Infer return type of async function
type AsyncReturnType<T extends (...args: any) => Promise<any>> = T extends (
...args: any
) => Promise<infer R>
? R
: never;
async function fetchPrompt(id: string) {
return { id, title: "Test" };
}
type PromptData = AsyncReturnType<typeof fetchPrompt>;
// { id: string; title: string }
// Extract props from component
type ComponentProps<T> = T extends React.ComponentType<infer P> ? P : never;
// Flatten array types
type Flatten<T> = T extends Array<infer U> ? U : T;
type PromptArray = Prompt[];
type SinglePrompt = Flatten<PromptArray>; // Prompt
// Check if type is array
type IsArray<T> = T extends any[] ? true : false;
```
## Mapped Types
Transform types with mapped types:
```typescript
// lib/types/mapped.ts
// Make specific keys optional
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type PromptWithOptionalTags = PartialBy<Prompt, "tags">;
// { id: string; title: string; content: string; tags?: string[] }
// Make specific keys required
type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
// Mutable - Remove readonly
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
// Get function parameter types
type FunctionParams<T extends (...args: any) => any> = T extends (
...args: infer P
) => any
? P
: never;
function createPrompt(title: string, content: string, tags: string[]) {
return { title, content, tags };
}
type CreatePromptParams = FunctionParams<typeof createPrompt>;
```
## Template Literal Types
Build type-safe string patterns:
```typescript
// lib/types/template-literals.ts
// API route types
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiVersion = "v1" | "v2";
type ApiRoute = `/${ApiVersion}/${string}`;
// "/v1/prompts", "/v2/users", etc.
// Event handler types
type DomEvent = "click" | "focus" | "blur" | "change";
type EventHandler = `on${Capitalize<DomEvent>}`;
// "onClick" | "onFocus" | "onBlur" | "onChange"
// CSS property types
type CSSUnit = "px" | "rem" | "em" | "%" | "vh" | "vw";
type CSSValue = `${number}${CSSUnit}`;
function setWidth(value: CSSValue) {
// value must be like "100px", "2rem", "50%"
}
setWidth("100px"); // OK
setWidth("2rem"); // OK
```
## Best Practices
1. **Start Simple**: Use built-in utilities before creating custom ones
2. **Meaningful Names**: Name utility types descriptively
3. **Documentation**: Document complex types with JSDoc comments
4. **Testing**: Test type utilities with type assertions
5. **Reusability**: Place common utilities in shared type files
6. **Performance**: Avoid overly complex recursive typesThis 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.