I'm working with an existing codebase that I'm introducting TypeScript too.
say I've got some frontend code that looks like this:
const res = await fetch('/api/user');
const user = res.json();
And my User interface looks like:
interface User {
name: string;
age;
}
I could just coerce the response from .json()
const user = res.json() as User;
But there is no guarantee that the backend is actually sending me the correct response and I'd rather be aware of that upfront. So my preference is to use a parsing function like:
function parseUser(input: any) : User {
try {
const user = {
name: input.name,
age: input.age
};
if (typeof user.name !== 'string' || typeof user.age !== 'number') {
throw new Error("Object had correct field, but wrong value types");
}
return user;
} catch(err) {
throw new Error("Error parsing user");
}
}
Now the thing is - for objects with much larger schemas, this would be hellish to write.
Is there some kind of utilty that can create these functions from my interface definitions?