| name | typescript-type-safe-api-contracts |
| version | 1.0 |
| description | TypeScript patterns for type-safe API contracts with strict typing and Zod integration. PROACTIVELY activate for: (1) designing type-safe API interfaces, (2) creating Zod schemas for validation, (3) implementing generic response wrappers. Triggers: "api design", "type safety", "zod validation"
|
| group | foundation |
| core-integration | {"techniques":{"primary":["structured_decomposition"],"secondary":[]},"contracts":{"input":"none","output":"none"},"patterns":"none","rubrics":"none"} |
TypeScript Type-Safe API Contracts
Core Principle: Explicit Return Types (Mandatory)
export function getUser(id: string) {
return db.user.findUnique({ where: { id } });
}
export async function getUser(id: string): Promise<User | null> {
return db.user.findUnique({ where: { id } });
}
Interface vs Type
Use interface for object shapes:
interface User {
id: string;
name: string;
email: string;
}
interface ApiResponse<T> {
success: boolean;
data: T;
}
Use type for unions, intersections, utilities:
type Status = 'pending' | 'active' | 'archived';
type ApiResult<T> =
| { success: true; data: T }
| { success: false; error: string };
Generic API Response Wrapper
export type ApiResponse<T> =
| ApiSuccessResponse<T>
| ApiErrorResponse;
export interface ApiSuccessResponse<T> {
success: true;
data: T;
}
export interface ApiErrorResponse {
success: false;
error: {
code: string;
message: string;
details?: Record<string, string[]>;
};
}
export async function createUser(data: CreateUserInput): Promise<ApiResponse<User>> {
}
Zod Integration (Runtime Validation)
import { z } from 'zod';
const userSchema = z.object({
name: z.string().min(1, 'Name required').max(100),
email: z.string().email('Invalid email'),
age: z.number().int().positive().optional(),
});
export type User = z.infer<typeof userSchema>;
export async function createUser(input: unknown): Promise<ApiResponse<User>> {
try {
const validated = userSchema.parse(input);
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid input',
details: error.flatten().fieldErrors,
},
};
}
}
}
Utility Types for Transformations
interface User {
id: string;
name: string;
email: string;
password: string;
}
type PublicUser = Pick<User, 'id' | 'name'>;
type UserWithoutPassword = Omit<User, 'password'>;
type PartialUser = Partial<User>;
type RequiredUser = Required<Partial<User>>;
type UserMap = Record<string, User>;
Anti-Patterns
Using any (FORBIDDEN):
function processData(data: any) { }
function processData(data: unknown) {
if (typeof data === 'string') {
}
}
Non-null assertion without guards:
const user = getUser()!;
const user = getUser();
if (!user) return;
For backend synchronization and Python/Pydantic mapping, see /api-contract command.