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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know to also convert the currencies const into a new type like this: type Currency = 'eur' | 'usd' | 'gbp' | 'chf'
type Currency = (typeof currencies)[number] already part of the answer 🙂 . type FiatExchangeRates = { [C in Currency]: number }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.