carlosbf
carlosbf

Reputation: 78

Usage of as keyword in typescript

In an object the developer defined code constants like this:

medium: {
      fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
      fontWeight: '500' as '500',
    },

What is the as keyword doing?

Upvotes: 0

Views: 275

Answers (2)

Zachary Haber
Zachary Haber

Reputation: 11037

What as '500' is doing in this case is setting up the fontWeight to be unable to be changed by making the fontWeight property of type '500' rather than type string which it would be without that line.

For example, in this Typescript Playground link, you'll notice that noWork has a type error when assigning a new value to fontWeight, while works allows it.

I've also added an example moreOptions with a string literal type union. As fontWeights generally only work with specific values, it's a great case for a union that will prevent invalid values from being assigned.

const noWork = {
  fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
  fontWeight: '500' as '500',
}
noWork.fontWeight='599' // Type '"599"' is not assignable to type '"500"'.

const works = {
  fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
  fontWeight: '500',
}
works.fontWeight='599'

const moreOptions = {
  fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
  fontWeight: '500' as '500'|'600'|'700',
}
moreOptions.fontWeight='600'
moreOptions.fontWeight='425' // Type '"425"' is not assignable to type '"500" | "600" | "700"'.

Limiting the types that are allowed for a variable is a very helpful part of typescript especially when there are certain values that work for a property.

Upvotes: 1

xandermonkey
xandermonkey

Reputation: 4422

In this case, as does nothing.

const x = '500';
const y = '500' as '500';
const z = '500' as string;

console.log(x === y);
console.log(z === y);
console.log(x === z);

Will output

true
true
true

A note I should add - TypeScript has something called string literal types which allow you to define the set of strings a variable is allowed to take. However, using them in this case is pointless because '500' is obviously already of type '500'.

Upvotes: 0

Related Questions