An API client uses (await response.json()) as Profile, where Profile contains a string username. If the server returns { "username": null }, does TypeScript prevent a runtime error? How should external JSON be checked?
Editorial starter question from DevCircle, provided for learning and discussion.
An assertion does not inspect incoming JSON. Treat external data as unknown and validate it before use.
ts
type Profile = { username: string };
function isProfile(value: unknown): value is Profile {
returntypeof value === "object" &&
value !== null &&
"username"in value &&
typeof value.username === "string";
}
const value: unknown = await response.json();
if (!isProfile(value)) thrownew Error("Invalid profile");
console.log(value.username.length);
This guard checks one field. Add length limits and nested checks for the actual contract. A schema validator can help with larger structures. A generic fetch wrapper that only casts to T has the same runtime gap.