Type Assertion
Question
What is a type assertion (as)?
Hint
Use assertions sparingly; they bypass type checking.
Explanation
A type assertion (value as Type) tells the compiler to treat a value as a specific type, overriding its inferred type. Unlike a cast in other languages, it is compile-time only — no runtime conversion. Use cases: 1) Narrowing a wider type (obj as SpecificType). 2) DOM types (document.querySelector("#x") as HTMLInputElement). 3) JSON parsing (JSON.parse(str) as MyType). Assertions bypass type checking — if wrong, you get runtime errors. Prefer type guards for safe narrowing. Use unknown instead of any for assertion targets. The angle-bracket syntax <Type>value is an alternative (not available in .tsx files).
Related Resources
Related Lessons
- Type Annotations
Learn annotations.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.