Build Advanced TypeScript Utility Types for Type-Safe Development
Create advanced TypeScript utility types including deep manipulation, branded types, and discriminated unions with tests.
๐ The Prompt
Create a comprehensive TypeScript utility types library for a [PROJECT_TYPE] project that enforces type safety across [DOMAIN_CONTEXT] (e.g., API responses, form handling, state management).
**Utility Types to Implement:**
1. **API Layer Types**:
- `ApiResponse<T>`: A discriminated union type with `success` and `error` variants, where the success variant contains `data: T` and the error variant contains `code: number` and `message: string`
- `PaginatedResponse<T>`: Extends `ApiResponse` with `meta: { page, perPage, total, totalPages }`
- `EndpointConfig<TParams, TBody, TResponse>`: Maps route parameters, request body, and response type for [NUMBER] endpoints: [ENDPOINT_LIST]
2. **Deep Manipulation Types**:
- `DeepPartial<T>`: Recursively makes all properties optional
- `DeepReadonly<T>`: Recursively makes all properties readonly
- `DeepRequired<T>`: Recursively makes all properties required
- `PathKeys<T>`: Extracts all valid dot-notation paths from a nested object type (e.g., `'user.address.city'`)
- `PathValue<T, P>`: Resolves the type at a given dot-notation path
3. **Domain-Specific Types**:
- `FormState<T>`: Maps each field of `T` to `{ value: T[K], error: string | null, touched: boolean, dirty: boolean }`
- `StrictOmit<T, K>`: Like `Omit` but enforces that `K` must be actual keys of `T`
- `RequireAtLeastOne<T, Keys>`: Ensures at least one of the specified keys is present
- `MutuallyExclusive<T, K1, K2>`: Ensures only one of two property groups can exist
4. **Validation & Guards**:
- Write type guard functions for each `ApiResponse` variant
- Create a `assertNever(x: never)` exhaustiveness checker
- Implement a `Brand<T, B>` type for nominal typing of [BRANDED_TYPES] (e.g., UserId, EmailAddress)
For each utility type, provide: the implementation, a JSDoc comment explaining usage, and at least 2 test cases using `type-testing` patterns (Expect<Equal<...>>) to prove correctness.
๐ก Tips for Better Results
Specify your TypeScript version (4.9+, 5.x) since newer versions support features like `satisfies` and `const` type parameters. Provide a real interface from your project as an example so the types are tailored to your data shapes. Ask for `.d.ts` declaration files if you plan to publish these as a shared package.
๐ฏ Use Cases
TypeScript developers and library authors use this when building type-safe foundations that eliminate runtime errors through compile-time checks across large codebases.