1

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?

1 Answer 1

1

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that has worked perfectly. I had no idea that Template Literal Types even existed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.