Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "as" keyword do?

if (process.env.NODE_ENV !== 'production') {     (WithUser as any).displayName = wrapDisplayName(Component, 'withUser'); } 

I'm not even sure if as is a keyword, but anyway, what does it do in JavaScript?

like image 270
Henok Tesfaye Avatar asked Apr 21 '19 09:04

Henok Tesfaye


People also ask

What does as do in JavaScript?

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.

What is identifier in TypeScript?

Identifiers in TypeScript Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.

What is type assertion?

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.

What does Colon do in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.


2 Answers

That is not vanilla JavaScript, it is TypeScript. As any means consider the typed object as a plain untyped JavaScrpt 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.

like image 116
Adrian Brand Avatar answered Sep 19 '22 12:09

Adrian Brand


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.

like image 38
P. Budiel Avatar answered Sep 17 '22 12:09

P. Budiel