Narrowing a known value
A value is typed as unknown, but prior application logic establishes a narrower type.
TypeScript · Const
The as operator is a compile-time type assertion that tells TypeScript to treat an expression as a chosen type. It performs no runtime conversion or validation.
The as operator tells TypeScript to treat an expression as a specified type for static checking. It does not validate, convert, or restructure the value, and it disappears from emitted JavaScript.
expression as Typeas changes the compiler’s view of a value; it is not a cast that transforms the value.expression as TargetType.as assertions have the same type-system meaning outside JSX.as syntax and prefix angle-bracket syntax.as rather than angle-bracket assertions in JSX or TSX files.const input: unknown = "TypeScript";
const length = (input as string).length;
console.log(length);The assertion lets the compiler treat the unknown value as a string so its length can be accessed.
A value is typed as unknown, but prior application logic establishes a narrower type.
DOM APIs or external boundaries provide a broad type while the program knows the expected element shape.
A generic or inferred expression needs to be viewed as a compatible, more specific type.
as operator do?as is a compile-time type assertion. It changes how TypeScript checks an expression but emits no runtime check or data conversion.
Follow-up: What happens if the assertion is wrong? The generated JavaScript still uses the original value, so runtime behavior can fail unless separate validation exists.
as compare with angle-bracket assertions?The as syntax and angle-bracket syntax express equivalent assertions. The as form is required in JSX because angle brackets conflict with JSX syntax.
Follow-up: How would you write an assertion in TSX? Use an expression such as value as HTMLElement, not <HTMLElement>value.
TypeScript permits an assertion when the source and target types have a sufficiently specific or general relationship. This prevents obviously impossible conversions such as asserting a string directly as a number.
Follow-up: What can be done when the compatibility rule is too conservative? An intermediate assertion through unknown or any can express the intended conversion, though it removes useful safety.
type annotationsunknownanyJSXangle-bracket syntax