Hello, This is the fourth article of the advanced typescript tutorial series. Today I'll cover small usage of
as const
Imagine you have some colors defined:
const Colors = {
cherry: "#F9193F",
mars: "#F19037",
meteor: "#FFE3C8"
}
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
Now if we type Colors.cherry
typescript will show us the real value of cherry color, which is #F9193F
!
Top comments (2)
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
Very nice, however i have an issue with trying to implement this.
When declaring av variable type inerhitance makes it so that i cannot change to another color.
Example
Does not work
let color = Colors.GRAY_LIGHT; // Inherits the actual color value as type.
color = Colors.RED; // Red does not have the same value so does not work.
Works but a little annoying to do.
let color: ColorType = Colors.GRAY_LIGHT;
color = Colors.RED;
Anyone have a suggestion on how to "fix" this?