Typed constants with Record in Typescript
When I define types in Typescript, I also define a list of valid options as an object so that I can reference it in the rest of my code. A type definition for a currency would for example with a list would look like the following.
export type Currency = 'EUR' | 'USD' | 'GBP';
export const Currencies = {
EUR: 'EUR',
USD: 'USD',
GBP: 'GBP',
};
In the rest of my code I can then use Currencies.EUR
and therefore have an autocomplete for the available currencies.
The only "danger" now is that I add another invalid Type to Currencies
or remove one currency from the Currency
type and forget to remove it from Currencies
. Thanks to Record
we can also prevent those issues. The final list would look like the following.
export const Currencies: Record<Currency, Currency> = {
EUR: 'EUR',
USD: 'USD',
GBP: 'GBP',
};