197
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?

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • 5
    Possible duplicate of [Any difference between type assertions and the newer \`as\` operator in TypeScript?](https://stackoverflow.com/questions/33503077/any-difference-between-type-assertions-and-the-newer-as-operator-in-typescript) – L Y E S - C H I O U K H Apr 21 '19 at 09:38
  • 'as' is type assertion expression used in Typescript – Prasad Apr 21 '19 at 09:39
  • 3
    Possible duplicate of [typescript. what is mean: (this as any)](https://stackoverflow.com/questions/42551681/typescript-what-is-mean-this-as-any) – jonrsharpe Apr 21 '19 at 09:40

7 Answers7

272

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.

solimant
  • 809
  • 9
  • 15
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • 27
    Please tell what `as` does if the asseration fail. Will a error or exception be thrown? – Grim Jun 26 '20 at 09:32
  • 29
    Nothing. It is purely a compiler concept to tell the compiler to consider an object a different type than it infers. The compiled JavaScript that actually runs has no concept of types. The code that runs will throw errors and exception based on the compiled JavaScript. – Adrian Brand Jun 26 '20 at 09:56
  • 8
    Could you please link any TypeScript documentation you referred to or that can support this answer? – Jeremy Jul 23 '20 at 20:49
  • 2
    Sometimes this "as" is only solution in ts apps,when some object havent exact type. – Goran_Ilic_Ilke Aug 18 '20 at 15:19
  • 1
    Documentation about `as` https://basarat.gitbook.io/typescript/type-system/type-assertion – Aleksander Ryhlitski Jan 13 '21 at 10:52
  • I've edited the answer to add an official link – mikemaccana May 19 '21 at 11:59
  • Note that `as` can also be used in another (more complex) context in typescript: `type CapitalizeKeys = {[key in keyof T as (key extends string ? Capitalize : key)]: T[key]}`. I'm afraid I haven't been able to determine the exact semantics of `as` in this context. – Claude Feb 23 '22 at 13:59
  • I have an error during compilation when I use 'as' in my .tsx file – amaugo somto Mar 14 '22 at 16:10
52

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.

Mateus Gondim
  • 5,362
  • 6
  • 31
  • 51
P. Budiel
  • 621
  • 5
  • 6
  • 4
    is there any difference between var b = 'test' as string; and var b: string = 'test' ? – Embedded_Mugs Jun 11 '21 at 03:26
  • 1
    @Embedded_Mugs to answer your question : https://stackoverflow.com/questions/69220403/is-there-a-difference-between-as-type-operator-and-classical-typing-in-typescr?noredirect=1#comment122344292_69220403 – TheSmartMonkey Sep 17 '21 at 11:53
15

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;
Aniket Gargya
  • 818
  • 1
  • 11
  • 21
Wassim Katbey
  • 298
  • 4
  • 9
  • 1
    This code generates: TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. – OSGI Java Jul 09 '21 at 13:40
  • 1
    If you know you want a number from a string then why not to write this instead? const accountCode = '123'; const castedAccountCode: number = parseInt(accountCode, 10); – OSGI Java Jul 09 '21 at 13:42
  • Or simply: const castedAccountCode: number = +accountCode; – Carlos Ribeiro Jun 27 '23 at 13:17
10

This kind of type assertion is useless, as

function foo (a: string, b: string): number {
    return (a as number) + (b as number)
}

simply transpiles to

function foo(a, b) {
    return a + b;
}

I first expected it to be something like

function foo(a, b) {
    if (typeof a != 'string') throw ...
    if (typeof b != 'string') throw ...
    return Number(a) + Number(b)
}

but no. TS gives users a wrong sense of security.

  • That's probably because the operator + is also valid for string, if you change 'string' for 'boolean' at the signature, the resulting code is the same, but you will have a compiler error. – QuarK May 22 '20 at 08:26
  • 17
    Once you understand what the point of 'as' is, then there really isn't a "wrong sense of security." – Richard.Davenport Jun 05 '20 at 16:13
  • 8
    `as` is used to help typescript check types at compile time, not for type coercion at runtime. – ABOS Jan 03 '21 at 02:23
  • @ABOS i was expecting that first code snippet meant third one !!! i am not able to understand what your comment meant to say !!! – Pravin Poudel Sep 18 '22 at 21:03
  • That’s just how Typescript works. You need to understand the difference between type space and value space in typescript to truly understand the behavior of “as”. – Liutong Chen Dec 25 '22 at 19:40
4

as above answers pointed the word as in the code of the original question is a keyword in TypeScript, however as a supplement, as is contextual keyword in JavaScript - when the code runs into the syntax rule ImportClause

hsy0
  • 139
  • 1
  • 9
3

Key Mapping via as

In the provided example of the OP the as keyword is used for Type Assertion. In TypeScript 4.1 and onwards the as keyword can not only be used for Type Assertion but also for Key Mapping. This allows you to re-map the keys of a type. E.g.:

type Person = {
  name: string;
  age: number;
};

type Getters<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
};

type MappedPerson = Getters<Person>;

// type MappedPerson = {
//   getName: () => string;
//   getAge: () => number;
// }

Generic & Template Literal Types really shine here. Key Mapping is a very mighty feature because you can also map a key to the type of it's value. For instance, with the help of Conditional Types it's possible to filter object properties by the type of a key's corresponding value . Let's say we want to remove all properties of type number on the Person type:

type WithoutPropertiesOfTypeNumber<T> = {
  [K in keyof T as T[K] extends number ? never : K]: T[K];
};

type PersonWithoutPropertiesOfTypeNumbers =
  WithoutPropertiesOfTypeNumber<Person>;

// type PersonWithoutPropertiesOfTypeNumbers = {
//     name: string;
// }
Behemoth
  • 5,389
  • 4
  • 16
  • 40
1

In TypeScript, the as keyword is used to explicitly type cast a value to a different type. It allows you to tell the TypeScript compiler that you know more about the type of a value than it does, and to treat that value as if it were of a different type.

For example, consider the following code:

let myValue: any = "Hello, world!";
let myLength: number = (<string>myValue).length;

In this code, myValue is of type any, which means that TypeScript doesn't know anything about its type. We can use the as keyword to tell TypeScript that we know myValue is a string, like this:

let myValue: any = "Hello, world!";
let myLength: number = (myValue as string).length;

Both examples achieve the same result, but the second example uses the as keyword to perform the type cast.

Note that when using the as keyword, you are telling TypeScript that you are sure of the type of the value. If you make a mistake and cast a value to the wrong type, it can cause runtime errors. Therefore, it's important to be careful when using the as keyword and make sure that you're casting to the correct type.

zhulien
  • 5,145
  • 3
  • 22
  • 36