QamoosTech
Programming FundamentalsTypes and typingIntermediateTypeScript

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 User compiles 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 chatReplace this as with a runtime check.
  • In an email or ticketValidate the response, then assert.