Wednesday, 7 April 2021
EVERYONE is on the TypeScript train nowadays, and for good reason.
But one thing that has really filled me with joy is const assertions
(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)
You can do some lovely shit with them, particularly with styled-components
. Take this simple map:
export const statusColours = {
success: '#91C699',
danger: '#E75C5E',
warning: '#E6AF5F',
progress: '#91C699',
} as const
In your components you can import statusColours
and call statusColours.success
to retrieve the hex code for the "success" status for example. But what if you wanted to add a new prop to a component that only allows one of the colours above and at the same time make it a nice API?
This is where the as const
assertion comes in handy. It allows you to "tokenize" the items in the object and make them available as a type.
Instead you can just create a new type like so:
export type StatusVariants = keyof typeof statusColours
Which produces:
And then in your component, you have this lovely fancy autocomplete:
Which is dynamically computed based on the keys in the statusColours
object.
I love TypeScript ❤️