2

I simply want to maintain an array of values that dynamically scales the type definition of FiatExchangeRates.

Any idea how to solve this?

const currencies = ['eur', 'usd', 'gbp', 'chf'] as const;

type FiatExchangeRates = {
    // ... how to get the following?
    // eur: number,
    // usd: number,
    // gbp: number,
    // chf: number,
}

const fiatExchangeRates: FiatExchangeRates = {
  eur: 1.11,
  usd: 1.12,
  gbp: 1.13,
  chf: 1.14,
};

const a = fiatExchangeRates.eur;

1 Answers1

3

You can extract tuple member type and use mapped type to create a desired one:

type FiatExchangeRates = { [K in (typeof currencies)[number]] : number }

Playground

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84