Type Assertions
Learn how to override TypeScript’s inferred type with the as keyword, and when it’s appropriate to do so.
Reading Time
12 min
Lesson
Lesson 15 of 30
What is a Type Assertion?
A type assertion tells the compiler "trust me, I know this value’s type better than you do" — it doesn’t perform any conversion or runtime check, it just changes how TypeScript treats the value at compile time.
A Basic Type Assertion
const input = document.getElementById("email") as HTMLInputElement;
console.log(input.value); // .value only exists on HTMLInputElement, not the generic HTMLElementCommon Use Case: DOM APIs
DOM methods like document.getElementById() return a broad type (HTMLElement | null) since TypeScript can’t know which specific element you meant — assertions are frequently used to narrow this to the actual element type.
Angle-Bracket Syntax (Non-JSX Files Only)
// Equivalent to the 'as' syntax, but not usable in .tsx files
const input = <HTMLInputElement>document.getElementById("email");Assertions Only Work Between Compatible Types
TypeScript still checks that an assertion is at least plausible — you can’t assert directly between two unrelated types without first going through unknown.
An Invalid Assertion
let value = "hello";
let num = value as number; // Error: Conversion may be a mistake
let num2 = value as unknown as number; // Allowed, but dangerous — you're overriding the safety net entirelyThe Non-Null Assertion Operator
A trailing ! tells the compiler a value is definitely not null or undefined, even though its type says it might be. It’s a narrower, more common form of assertion.
Non-Null Assertion
function getElement(id: string): HTMLElement | null {
return document.getElementById(id);
}
const el = getElement("app")!; // asserts the result is not null
el.textContent = "Loaded";Assertions Are Not Runtime Checks
A type assertion doesn’t validate anything — if you assert incorrectly, TypeScript won’t catch the mistake, and it will surface as a runtime error instead, exactly the kind of bug TypeScript is meant to prevent.
Best Practice
Use assertions sparingly, and only when you genuinely know more than the compiler (like knowing which specific DOM element an id belongs to). Prefer proper narrowing (typeof, instanceof, custom type guards) whenever it’s possible instead.