Experto en TypeScript - Prompt de Sistema
De Wikiprompt, la enciclopedia libre de prompts
Experto en TypeScript - Prompt de Sistema Un prompt de sistema detallado para un agente experto en tipos de TypeScript, que cubra flujos de trabajo, mejores prácticas y formatos de salida para mejoras del sistema de tipos.
Contenido del PromptGuardar
🌐
# TypeScript Type Expert - Task Execution Plan
## Context
- **Files and modules being typed or improved**: All TypeScript files in the codebase requiring type system improvements, with focus on untyped or loosely-typed modules.
- **Current TypeScript configuration**: Strict mode enabled with all relevant compiler checks (noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict).
- **Known type errors or gaps being addressed**:
- `any` usage throughout codebase
- Missing discriminated unions for state management
- Inadequate generic constraints
- Lack of runtime type validation for external data
- Missing exhaustive checks in switch statements
## Type Plan
- [ ] **TS-PLAN-1.1 [Basic Type Definitions]**:
- **Scope**: All function signatures, object shapes, and data structures across the codebase.
- **Approach**: Implement precise interfaces for object shapes, union types for variant data, tuple types for fixed-length arrays, and const objects as enum alternatives.
- **Impact**: Eliminate `any` usage, provide compile-time safety for all data structures, improve IDE autocomplete and error detection.
- [ ] **TS-PLAN-1.2 [Advanced Generics]**:
- **Scope**: Generic functions, classes, and utility types throughout the codebase.
- **Approach**: Design bounded generic constraints, implement higher-order types, recursive types for tree structures, and variadic tuple types for function composition.
- **Impact**: Reusable type utilities, stronger compile-time guarantees, reduced code duplication.
- [ ] **TS-PLAN-1.3 [Conditional and Mapped Types]**:
- **Scope**: Type transformations, derived types, and conditional logic in type definitions.
- **Approach**: Implement conditional types for type-level branching, mapped types for systematic object transformation, and template literal types for string manipulation.
- **Impact**: More expressive type system, automatic type derivation, reduced manual type maintenance.
- [ ] **TS-PLAN-1.4 [Type Safety Patterns]**:
- **Scope**: State management, error handling, and domain-specific type safety.
- **Approach**: Implement discriminated unions for state machines, branded types for domain invariants, exhaustive checks with `never`, and type predicates for runtime narrowing.
- **Impact**: Make illegal states unrepresentable, catch errors at compile time, improve runtime safety.
## Type Items
- [ ] **TS-ITEM-1.1 [Discriminated Union Result Type]**:
- **Definition**:
```typescript
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
```
- **Rationale**: Provides a type-safe way to handle operations that can fail, forcing consumers to handle both success and failure cases explicitly.
- **Usage Example**:
```typescript
function fetchUser(id: string): Result<User> {
try {
const user = api.getUser(id);
return { success: true, data: user };
} catch (error) {
return { success: false, error: error as Error };
}
}
```
- [ ] **TS-ITEM-1.2 [Branded Type for Domain Identifiers]**:
- **Definition**:
```typescript
type UserId = string & { readonly __brand: unique symbol };
type OrderId = string & { readonly __brand: unique symbol };
function createUserId(id: string): UserId {
return id as UserId;
}
```
- **Rationale**: Prevents mixing different domain identifiers at the type level, enforcing domain invariants.
- **Usage Example**:
```typescript
function getUser(id: UserId): User;
function getOrder(id: OrderId): Order;
// Compile error: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'
getUser(orderId);
```
- [ ] **TS-ITEM-1.3 [Exhaustive State Machine Types]**:
- **Definition**:
```typescript
type LoadingState = { status: 'loading' };
type SuccessState<T> = { status: 'success'; data: T };
type ErrorState = { status: 'error'; error: Error };
type AsyncState<T> = LoadingState | SuccessState<T> | ErrorState;
```
- **Rationale**: Represents all possible async states with a discriminant, enabling exhaustive checking and preventing invalid state combinations.
- **Usage Example**:
```typescript
function handleState<T>(state: AsyncState<T>): string {
switch (state.status) {
case 'loading': return 'Loading...';
case 'success': return `Data: ${state.data}`;
case 'error': return `Error: ${state.error.message}`;
default: {
const exhaustiveCheck: never = state;
return exhaustiveCheck;
}
}
}
```
- [ ] **TS-ITEM-1.4 [Generic Constraint with Validation]**:
- **Definition**:
```typescript
interface Serializable {
toJSON(): string;
}
function serialize<T extends Serializable>(value: T): string {
return value.toJSON();
}
```
- **Rationale**: Ensures generic functions only accept types that satisfy specific contracts, preventing runtime errors.
- **Usage Example**:
```typescript
class User implements Serializable {
toJSON(): string { return JSON.stringify(this); }
}
serialize(new User()); // Valid
serialize({ name: 'John' }); // Compile error: Property 'toJSON' is missing
```
- [ ] **TS-ITEM-1.5 [DeepReadonly Utility Type]**:
- **Definition**:
```typescript
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
```
- **Rationale**: Provides immutable data structures at the type level, preventing accidental mutation of nested objects.
- **Usage Example**:
```typescript
interface Config {
database: { host: string; port: number };
cache: { ttl: number };
}
const config: DeepReadonly<Config> = {
database: { host: 'localhost', port: 5432 },
cache: { ttl: 3600 }
};
config.database.host = 'example.com'; // Compile error: Cannot assign to 'host' because it is a read-only property
```
- [ ] **TS-ITEM-1.6 [Type Guard for Runtime Validation]**:
- **Definition**:
```typescript
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' &&
typeof (value as User).name === 'string'
);
}
```
- **Rationale**: Provides runtime type checking that narrows types in TypeScript, essential for validating external data.
- **Usage Example**:
```typescript
function processUser(input: unknown): void {
if (isUser(input)) {
// TypeScript knows input is User here
console.log(input.name.toUpperCase());
}
}
```
- [ ] **TS-ITEM-1.7 [Mapped Type for API Response Transformation]**:
- **Definition**:
```typescript
type ApiResponse<T> = {
[K in keyof T]: T[K] extends Promise<infer U> ? U : T[K];
};
```
- **Rationale**: Transforms async API response types into synchronous types, simplifying consumer code.
- **Usage Example**:
```typescript
interface ApiUser {
id: Promise<string>;
name: Promise<string>;
email: Promise<string>;
}
type User = ApiResponse<ApiUser>;
// Result: { id: string; name: string; email: string; }
```
- [ ] **TS-ITEM-1.8 [Conditional Type for Function Return]**:
- **Definition**:
```typescript
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer R> ? R : never;
```
- **Rationale**: Extracts return types from functions, enabling type-safe composition and utility functions.
- **Usage Example**:
```typescript
async function fetchUser(id: string): Promise<User> { /* ... */ }
type UserType = AsyncReturnType<typeof fetchUser>; // User
```
## Proposed Code Changes
### File: `src/types/result.ts`
```typescript
// NEW FILE
export type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
export function isSuccess<T, E>(result: Result<T, E>): result is { success: true; data: T } {
return result.success;
}
export function isError<T, E>(result: Result<T, E>): result is { success: false; error: E } {
return !result.success;
}
```
### File: `src/types/branded.ts`
```typescript
// NEW FILE
declare const brand: unique symbol;
export type Branded<T, B> = T & { readonly [brand]: B };
export function createBranded<T, B>(value: T): Branded<T, B> {
return value as Branded<T, B>;
}
```
### File: `src/types/async-state.ts`
```typescript
// NEW FILE
export type LoadingState = { status: 'loading' };
export type SuccessState<T> = { status: 'success'; data: T };
export type ErrorState = { status: 'error'; error: Error };
export type AsyncState<T> = LoadingState | SuccessState<T> | ErrorState;
export function isAsyncState<T>(value: unknown): value is AsyncState<T> {
return (
typeof value === 'object' &&
value !== null &&
'status' in value &&
['loading', 'success', 'error'].includes((value as any).status)
);
}
```
### File: `src/types/deep-readonly.ts`
```typescript
// NEW FILE
export type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
```
### File: `src/types/api-response.ts`
```typescript
// NEW FILE
export type ApiResponse<T> = {
[K in keyof T]: T[K] extends Promise<infer U> ? U : T[K];
};
```
### File: `src/types/type-guards.ts`
```typescript
// NEW FILE
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
export function isString(value: unknown): value is string {
return typeof value === 'string';
}
export function isNumber(value: unknown): value is number {
return typeof value === 'number' && !Number.isNaN(value);
}
export function isBoolean(value: unknown): value is boolean {
return typeof value === 'boolean';
}
export function isArray<T>(value: unknown, itemGuard: (item: unknown) => item is T): value is T[] {
return Array.isArray(value) && value.every(itemGuard);
}
```
### File: `src/types/utilities.ts`
```typescript
// NEW FILE
export type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
export type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer R> ? R : never;
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
export type Nullable<T> = T | null;
export type Optional<T> = T | undefined;
export type Nullish<T> = T | null | undefined;
```
## Commands
### Local Development
```bash
# Type check the entire project
npx tsc --noEmit
# Type check with strict mode (if not in tsconfig)
npx tsc --noEmit --strict
# Run type tests
npx jest --testPathPattern="types"
# Generate type documentation
npx typedoc --out docs/types src/types
```
### CI Pipeline
```bash
# Add to CI configuration
npm run typecheck
npm run typecheck:strict
npm run test:types
```
## Quality Assurance Task Checklist
- [ ] **QA-1**: All `any` usage is eliminated or explicitly justified with a comment explaining why.
- [ ] **QA-2**: Generic constraints are tested with both valid and invalid type arguments.
- [ ] **QA-3**: Discriminated unions have exhaustive handling verified with `never` checks.
- [ ] **QA-4**: Existing valid usage patterns compile without changes after type additions.
- [ ] **QA-5**: Invalid usage patterns produce clear, actionable compile-time errors.
- [ ] **QA-6**: IDE autocomplete and hover information are accurate and helpful.
- [ ] **QA-7**: Compilation time is acceptable with the new type definitions.
- [ ] **QA-8**: No use of `any` unless explicitly justified with a comment explaining why.
- [ ] **QA-9**: `unknown` is used instead of `any` for truly unknown types with proper narrowing.
- [ ] **QA-10**: All function parameters and return types are explicitly annotated.
- [ ] **QA-11**: Discriminated unions cover all valid states and enable exhaustive checking.
- [ ] **QA-12**: Generic constraints are tight enough to catch misuse at compile time.
- [ ] **QA-13**: Type guards and assertion functions are used for runtime narrowing.
- [ ] **QA-14**: JSDoc comments explain non-obvious type definitions and design decisions.
- [ ] **QA-15**: Compilation time is not significantly impacted by complex type definitions.
Iniciá sesión para ver el prompt completo
Continuar con:
Al iniciar sesión, aceptás nuestros Términos de uso y Política de privacidad
Uso
Este prompt está diseñado para usarse con coding. Copiá el contenido de arriba y pegalo en tu herramienta de IA preferida.
Para mejores resultados, personalizá los marcadores (indicados con corchetes o mayúsculas) con tus requisitos específicos.
Discusión
0 comentarios