Middle
How to type an API response if the contract is not perfect?
sobes.tech AI
Answer from AI
If the API contract is not perfect (for example, fields may be missing, have different types or structures), response typing can be made more flexible:
- Use optional fields (
?in TypeScript) for optional data. - Apply union types to account for possible variations.
- Use the
unknownoranytype for parts of data with unpredictable structure, with subsequent type checking and casting. - Create interfaces with the minimally necessary fields and extend them as the contract becomes clearer.
- Use validation and parsing libraries (e.g.,
io-ts,zod) to safely transform and validate data at runtime.
Example in TypeScript:
interface ApiResponse {
id: number;
name?: string; // field may be missing
data: string | null; // can be a string or null
extra?: unknown; // unknown structure
}
This approach allows working with real data without breaking type safety and maintaining code security.