DEV Community

Artur Czemiel
Artur Czemiel

Posted on

TypeScript Tutorial - Use "as const" to export colors!

Hello, This is the fourth article of the advanced typescript tutorial series. Today I'll cover small usage of

as const
Enter fullscreen mode Exit fullscreen mode

Imagine you have some colors defined:

const Colors = {
  cherry: "#F9193F",
  mars: "#F19037",
  meteor: "#FFE3C8"
}
Enter fullscreen mode Exit fullscreen mode

When you try to use them somewhere else TypeScript will show you type of the Colors.cherry is string. This is ok if we have 3 colors, but what if we have 50 colors with strange names? We can use new typescript as const or <const>:

const Colors = {
  cherry: "#F9193F",
  mars: "#F19037",
  meteor: "#FFE3C8"
} as const
Enter fullscreen mode Exit fullscreen mode

Now if we type Colors.cherry typescript will show us the real value of cherry color, which is #F9193F !

Discussion (1)

Collapse
phytertek profile image
Ryan Lowe

very cool write up! might I suggest adding a sightly more complex (albeit contrived) example such as

const foo= {
one: 'one',
two: 'two',
three: ['three']
} as const

to demonstrate a complex type difference, ie three = a tuple with 'three' vs string[]
rather than just a string enum equivalent