Type Assertions & Casting
Tell the TypeScript compiler about the type of a value when you know more specific information than TypeScript can infer automatically.
1. The `as` Assertion Operator
// Telling TypeScript that DOM element is HTMLInputElement
const emailInput = document.getElementById("email") as HTMLInputElement;
// Accessing input specific property safely!
emailInput.value = "user@example.com";2. Non-Null Assertion Operator (`!`)
Assert that an expression is neither null nor undefined when you are 100% certain:
function processElement(element?: HTMLElement) {
// Postfix ! tells TypeScript element is NOT undefined
element!.focus();
}3. The `satisfies` Operator (TS 4.9+)
The satisfies operator validates that an object matches a type contract without changing or widening its inferred property types:
type Color = string | [r: number, g: number, b: number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<string, Color>;
// Both satisfies type validation AND keeps exact method autocomplete!
palette.green.toUpperCase(); // Works! Knows green is string
palette.red.map(x => x); // Works! Knows red is arrayNext Up
Learn TypeScript with React: typing props, useState, useRef, and form events.
Next Lesson: TypeScript with React →