skip to Main Content

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


  1. If you declare your CURRENCIES array with a const assertion, you can just do the following:

    export const CURRENCIES = ['EUR', 'CHF', 'GBP', 'USD', 'DKK'] as const;
    
    type Currency = typeof CURRENCIES[number];
    // type Currency = "EUR" | "CHF" | "GBP" | "USD" | "DKK"
    
    Login or Signup to reply.
  2. 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 your InputProps and CurrencyInput to accept any currency code from the CURRENCIES array:
    Try this and see if it works:

    export const CURRENCIES = ['EUR', 'CHF', 'GBP', 'USD', 'DKK'];
    
    export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
      currency?: typeof CURRENCIES[number]; // Use the type from the CURRENCIES array
    }
    
    const CurrencyInput = ({ currency = 'EUR' }: InputProps) => {
      // Your component implementation here
    };
    

    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 the CURRENCIES array.

    Hope it helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search