liveBook · Manning

As operator

As explained in Secrets of the JavaScript Ninja, Third Edition

TypeScript syntax for asserting a compile-time type for an expression without changing its runtime value.

The `as` operator tells TypeScript’s type checker that an expression has a particular type. It can help when a type predicate leads to an incorrect inference, but it does not change the expression’s runtime value. Use it cautiously: the checker can only rely on the type information you provide. section 2.1.3

Override an incorrect inference

if (isShortString(stringOrNumber)) { const shortString = stringOrNumber as string; // type: string // ... } section 2.1.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Demonstrates a type assertion after a predicate and cautions that inaccurate type information can mislead the checker.
Examples
Uses a string-or-number value asserted as a string inside a type-predicate branch.
What you can do after
Apply `as` to tell TypeScript the type of an expression when its inference is unsuitable.
How it connects
Connects type assertions with type predicates and type narrowing.

Also explained in

Compare how 4 books explain as operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.