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)