../courses.php
TypeScript
TS107
3
APIs Need Typed Data
Typed API shapes help frontend and backend code agree on what data should look like.
Why do APIs need typed data?
APIs need typed data because the code sending data and the code receiving data must agree on property names, value types, and missing-value rules.
APIs move data between systems.
One side sends a request or response.
The other side expects a certain shape.
If the shape is wrong, the application may break in confusing ways.
TypeScript helps describe these shapes clearly before runtime.
Typing an API response
type ApiUser = {
id: number;
email: string;
active: boolean;
};
function showUser(user: ApiUser): void {
console.log(user.email);
}
ApiUser describes the expected API data shape.
id must be a number.
email must be a string.
active must be a boolean.
The function expects data that follows this shape.
Agreement
API producers and consumers need the same expectations.
Shape
Types describe required fields.
Errors
Wrong API data becomes easier to find.
Teams
Frontend and backend developers can share a clearer contract.
Unknown API shape
function showUser(user: any) {
console.log(user.email);
}
Typed API shape
function showUser(user: ApiUser): void {
console.log(user.email);
}
Ask ChatGPT: "Create a TypeScript type for this API response and explain which fields are required."
Create a type for an API user.
Add id, email, and active fields.
Write a function that receives the typed API user.
Try passing an object with a missing email.
Explain why API shapes need contracts.
Using any for all API data.
Assuming the backend always sends the expected shape.
Forgetting required properties.
Not handling missing or optional fields.
Confusing compile-time types with runtime validation.
Use TypeScript types to describe simple API data shapes.
Login - Jit4All
Login
Welcome back to Jit4All