Type Assertion (TypeScript)
A type assertion tells the compiler to treat a value as a specific type, using the `as` keyword. You are overriding TypeScript's inference because you know more about the type than it does.
TypeScript
Assertions don't change the value or do any runtime conversion — they only adjust how the compiler sees it. A common use is when you grab a DOM element and need to tell TypeScript its exact element type.
Use assertions carefully: if your claim is wrong, you've silenced a real error. They are a promise to the compiler, not a check.
Syntax
value as TypeExamples
TypeScript
const input = document.getElementById("name") as HTMLInputElement;
console.log(input.value);TypeScript
let data: unknown = "42";
let text = data as string;
console.log(text.length);Output:
2