Home > OS >  Appending a string to a TypeScript object type, where property names are derived from a string liter
Appending a string to a TypeScript object type, where property names are derived from a string liter

Time:07-26

I would like to dynamically define a type like this from a list of currency ids:

{
  usd: number;
  usd_mcap: number;
  eur: number;
  eur_mcap: number;
  gbp: number;
  gbp_mcap: number;
}

I have the following, but I cannot figure out how to add the {currency}_mcap property to the object:

type CurrencyId = 'usd' | 'eur' | 'gbp';
type AssetInfo = {
  [key in CurrencyId]: number;
} & {
  [(key   '_mcap') in CurrencyId]: number; // This does not work
}

Any ideas what I can try?

CodePudding user response:

You can use Template Literal Types for this:

type CurrencyId = 'usd' | 'eur' | 'gbp';

// as a Record
type AssetInfoRecord = Record<CurrencyId | `${CurrencyId}_mcap`, number>;

// as an Object
type AssetInfoObject = {
  [key in CurrencyId | `${CurrencyId}_mcap`]: number;
};
  • Related