What does the "as" keyword do?

That is not vanilla JavaScript, it is TypeScript. as any tells the compiler to consider the typed object as a plain untyped JavaScript object.

The as keyword is a Type Assertion in TypeScript which tells the compiler to consider the object as another type than the type the compiler infers the object to be.


It's TypeScript, not vanilla JS, but for the as itself: It's called Type Assertion, you are just telling the compiler to treat something as a type:

var a = 'TEST STRING'
var b = a as string; //Means the compiler will assume it's a string

It's equivalent to this:

var a = 'TEST STRING'
var b = <string> a; 

However it might be confusing when working with JSX (JS with html tags) , so in those cases the as syntax is preferred.


This is a Typescript operator, it's not available in ECMAScript 2015 (latest release of Javascript)

As the answers above indicated, the 'as' operator is a form of Type Assertion

To take a short example, say you have two types: First & Second. You're writing a method, and the method doesn't exactly know which type your object will be of. It could be of type First or Second.

So, you declare your variable without a strict type. Once your method is aware of the type your variable should take on, you can return it 'as that type'.

That seemed a little vague and ambiguous, but the 'as' operator actually performs the exact same function as another (more familiar) pattern:

These two snippets of code do the exact same thing

    let accountCode = '123';
    let castedAccountCode = <number>accountCode;

Using as keyword:

    let accountCode = '123';
    let castedAccountCode = accountCode as number;