Home > OS >  TS create keys of new type from array of strings
TS create keys of new type from array of strings

Time:10-25

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;

CodePudding user response:

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

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

Playground

  • Related