as and satisfiesTypeScript casting (formally called type assertions) tells the compiler to treat a value as a more specific type using the as keyword. Unlike casting in C# or Java, TypeScript as performs zero runtime conversion—it only changes how the compiler sees the variable.
Use assertions sparingly, primarily when narrowing DOM elements like document.getElementById("email") as HTMLInputElement where you know more than static analysis can prove.
as Assertions vs. TypeScript 4.9 satisfiesPrefer satisfies when you want to verify that an object matches a type without erasing the exact literal keys and value types you wrote.
const palette = {
primary: [37, 99, 235],
accent: "#10b981",
} satisfies Record<string, string | number[]>;
// TypeScript remembers accent is a string and primary is a number[]!
console.log(palette.accent.toUpperCase());
console.log(palette.primary.map((c) => c + 1));
// Typical browser usage:
// const input = document.querySelector("#username") as HTMLInputElement | null;
// if (input) console.log(input.value);
as to silence real API bugs: Writing const data = (await res.json()) as User skips runtime validation; if the server returns { error: "Not found" }, your app crashes later.<Type>value angle-bracket syntax in .tsx files: <HTMLInputElement>el conflicts with React JSX tags; always use el as HTMLInputElement everywhere.value as unknown as Target: Double assertions force completely unrelated types together and usually hide a design bug.value as number convert a string "42" into the number 42?No. as disappears completely in compiled JavaScript. Call Number(value) or parseInt(value, 10) to actually convert data at runtime.
! do?Appending ! (like user!.name) tells TypeScript "trust me, this is neither null nor undefined." Prefer an explicit if (user) check whenever possible.
("hello" as number)?TypeScript blocks single as assertions between types that do not overlap at all, helping catch obvious mistakes unless you intentionally route through unknown.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.