Type Assertion
PronunciationTYPE uh-SER-shun
Definition
A type assertion tells the type checker "treat this value as this type" (for example value as User in TypeScript). It changes only what the checker believes, not what the value really is at run time.
Where you hear it
In TypeScript code reviews (as and !), API response handling and migration from JavaScript.
Examples
response as Usercompiles even if the server sends something else.Prefer a type guard over an assertion.
The cast to User is an assertion, so a wrong payload fails later, at run time.
Common mistake
Using assertions to silence errors. If the value isn't what you claimed, the bug appears later at run time.
Don't confuse with
Type narrowing, where code checks the value (typeof x === 'string') so the checker can prove the type.
Say it at work
- In a meeting or chat
Replace this
aswith a runtime check. - In an email or ticket
Validate the response, then assert.
Keep exploring
More in Programming Fundamentals