The as Keyword for Type Assertions
Override inferred types deliberately with as.
What Is a Type Assertion?
A type assertion tells the compiler 'trust me, I know this value is of type T.' You use the as keyword: value as Type. It changes how the type checker sees the value, not the value itself.
const raw: unknown = 'hello world';
const text = raw as string;
console.log(text.toUpperCase());The as Syntax
Write the expression, then as, then the target type. There's an older angle-bracket syntax too, but as is preferred because it works everywhere, including JSX/TSX files.
const value: unknown = 42;
const n = value as number;
console.log(n + 8);All lessons in this course
- The as Keyword for Type Assertions
- Non-null Assertion Operator
- Double Assertions and Their Risks
- Assertions vs Type Guards