

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: The Runtime Problem
incomplete
2: Validation Libraries
incomplete
3: Schemas and Type Inference
incomplete
4: Why Validate?
incomplete
This lesson's interactive features are locked, please to keep using them
TypeScript gives us compile-time type safety, but when data comes from external sources like APIs, we lose that safety. The result of await res.json() is typed as any.
const res = await fetch(
"https://api.boot.dev/v1/courses_rest_api/learn-http/issues",
);
const data = await res.json(); // data is type 'any'
console.log(data[0].title.toUpperCase()); // might crash at runtime!
Without a library, you'd need to manually check every field, which is tedious, error-prone, and doesn't give you TypeScript types:
function validateUser(data: any): User {
if (!data || typeof data !== "object") {
throw new Error("Invalid data");
}
if (typeof data.name !== "string") {
throw new Error("Invalid name");
}
if (typeof data.age !== "number") {
throw new Error("Invalid age");
}
// ... and so on for every field
return data;
}
Or, if you trust the backend or feel adventurous, you can forcefully assert it:
function validateUser(data: any): User {
return data as User;
}
Since any is assignable to everything, you don't need as User, but writing it makes your intent clear.
The Jello API returns an array of issue data, but we can't trust the shape. Create manual validation functions that:
id (string)title (string)