TypeScript types stop at runtime
Validate unknown input even when the rest of the program is typed.
Compile-time versus runtime
TypeScript checks code before it runs. A response from fetch, local storage, or a form can still contain unexpected values. Keep external input as unknown until a runtime check proves its shape; a type assertion does not perform that check.
Narrow deliberately
Check the container first, then each required property. Keep optional values optional rather than substituting a misleading default. After validation, return a small typed object that the rest of the application can trust.
function isUser(value: unknown): value is { id: number; name: string } {
return typeof value === 'object' && value !== null
&& 'id' in value && typeof value.id === 'number'
&& 'name' in value && typeof value.name === 'string';
}
Validate the entire shape
Checking that a response is an object is only the first step. Arrays are objects too, and nested fields may be absent or malformed. Validate each field your UI will read, including the shape of arrays and optional fields. Return a useful validation error so the view can show a failure state instead of throwing while rendering.
Make the trusted zone small
Parse data once near fetch or storage, then pass a typed result inward. Avoid scattering `as User` throughout components; each assertion hides a possible mismatch. Tests should use a valid payload, a missing field, an unexpected type, and a null response. When a server contract changes, the parser becomes the obvious place to update.
Check your understanding
Does `response as User` make an API response safe to use?
Show explanation
No. It only tells the compiler to trust the value. Validate the response at runtime first.
You can read for free. Create an account to save your progress.
Next lesson: Build a keyboard-usable control →Put this lesson into practice
A practice activity at this level in the same module.
Try: Fix a loose-equality bugFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.