I have a list of currencies supported
export const CURRENCIES = ['EUR', 'CHF', 'GBP', 'USD', 'DKK'];
This is defined in a npm library.
I have a TS project where I am using currency code for a currency related component. This is the current implementation.
export Interface InputProps extends React.InputHTMLAttributes<HTMLInputElement>{
currency?: 'USD' | 'EUR' | 'GBP'; // current implementation
}
const CurrencyInput = ({ currency = 'EUR'}:InputProps) => {
....
}
However, with the current implementation, the currency prop is restricted only to ‘USD’, ‘EUR’, and ‘GBP’. I want to make the currency prop dynamic, so it can accept any currency code from the CURRENCIES array. I prefer to keep the supported currencies in the npm library, so that if I have to update the supported currency in future, i only need to update in one place because this currency constant is being used in multiple places.
2
Answers
If you declare your
CURRENCIES
array with aconst
assertion, you can just do the following:You can achieve this by using TypeScript’s string literal types in combination with the
CURRENCIES
array defined in your npm library. Here’s how you can modify yourInputProps
andCurrencyInput
to accept any currency code from theCURRENCIES
array:Try this and see if it works:
By using
typeof CURRENCIES[number]
as the type for the currency property, you are specifying that it should accept any value that is present in theCURRENCIES
array.Hope it helps!