Search code examples
typescripttscreact-native-paper

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?


Solution

  • 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.