Wrong type assertion hides runtime error
Quick summary
You used 'as Type' to override the inferred type — TypeScript stops checking, and the wrong type causes a runtime error.
Why this happens
You used 'as' to cast a value to a type it is not actually compatible with at runtime
A double assertion (as unknown as Type) was used to bypass all type safety checks
The asserted type does not match the actual runtime shape of the data from an API or parsed JSON
Minimal example
const data: unknown = JSON.parse('{"name": 123}');
const user = data as { name: string };
console.log(user.name.toUpperCase()); // runtime error: toUpperCase is not a functionconst data: unknown = JSON.parse('{"name": 123}');
if (typeof data === 'object' && data !== null && typeof (data as any).name === 'string') {
console.log((data as any).name.toUpperCase()); // safe
} else {
console.log('Invalid data shape');
}Replacing the assertion with a runtime type guard checks the actual shape before accessing properties, preventing the runtime error.
How to diagnose
Remove the 'as' assertion and see what compile error TypeScript reports — that is the real type issue
Use a runtime type guard or schema validation (zod, io-ts) to verify the actual shape before asserting
Log the runtime value and compare its shape with the asserted type to find mismatches
How to fix
Replace 'as Type' with a runtime type guard function that checks the shape before using the value
Use a schema validation library like zod to parse and validate unknown data at runtime
Fix the underlying type issue so the assertion is unnecessary — let TypeScript infer the correct type
How to prevent
Avoid 'as' assertions for data from external sources — use runtime validation instead
Enable strict type checking and fix type errors properly rather than suppressing with 'as'
Related Resources
Related Glossary
Related Lessons
- Type Assertions
Learn about type assertions.