type assertion (TypeScript)
Writing value as Type to tell the compiler to treat a value as a type, without any check that it really is.
A wrong assertion silences the compiler and lets invalid data through unchecked.
In more detail
An assertion overrides the compiler rather than proving anything, so a wrong one moves the failure to run time. Prefer type guards, validation or satisfies. The special form as const is safe because it only makes types narrower.
Related terms
- type predicate — A return type written param is Type, which tells the compiler that when the function returns true, the argument has that type.
- satisfies — An operator, value satisfies Type, that checks a value matches a type without changing the value's own, more precise inferred type.
- as const — The TypeScript suffix as const, which tells the compiler to treat an object's values as fixed literal values rather than general types.
- untrusted input — Any data a program did not create itself, including arguments, form fields, request bodies, file contents, file names and environment variables.
Taught in
- any Versus unknown: Defensive Typing In Practice — Production TypeScript
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Custom Type Predicates: Functions Returning is Type — Production TypeScript
- Generic Interfaces, Classes And Type Aliases — Production TypeScript
- Function Utilities: ReturnType, Parameters And Constructor — Production TypeScript
- Declaration Files, Ambient Namespaces And Module Augmentation — Production TypeScript