What's the purpose of 'as' keyword in typescript?

Viewed 2757
class Hero {
  name: string = ''
}

const heroes: Hero[] = [];
const heroes2 = [] as Hero[];

I noticed there are these two separate ways of declaring an array in TypeScript. I wonder if this is just syntactical sugar, or is there some underlying logic I am missing?

3 Answers

In your example you are telling the compiler the type of a variable as you create it, and the two ways you demonstrate are interchangeable. However the as operator is more frequently used within a code block to cast a variable from one type to another, rather than during the definition of the variable where the :type format is more frequently used.

Some pseudo code using your Hero example:

function X() : any { 
    return <something> // where <something> is an object which we actually know to be a Hero object but for some external reason don't or can't declare the return type in the function definition
}

function doStuff() {
    if ((X() as Hero).name == 'Bilbo') {
        print('We found the hero from LOTR')
    }
}

x

They are two ways of expressing the same thing. The as keyword is used to perform a type assertion, in this case

const heroes2 = [] as Hero[];

tells the compiler to create the heros2 array and interpret it as an array of type Hero. On the other hand

const heroes: Hero[] = [];

is explicit declaration, the canonical way to do it. In the end it is syntactic sugar really so use whatever way you think reads best.

To notice the difference, look at the following snippet:

class Hero {
  name: string = ''
}

// `hero` is defined to have type `Hero`. So we get an error on this line,
// because `extra` is not part of `Hero`.
const hero: Hero = {name: '', extra: ''};

// The following definition does not throw error.
// Here, we are casting the object to Hero.
// The object itself conforms to `Hero` type as it contains the necessary properties. 
const hero2 = {name: '', extra: ''} as Hero;

Playground Link

Also see https://basarat.gitbook.io/typescript/type-system/type-assertion#assertion-considered-harmful

Related