简体   繁体   中英

How to set typescript type for key value in objects?

I have an object of currency types with properties like this:

CurrencyType = {
  usd: {
    country: 'United States', 
    symbol: '$USD', 
    icon: <USD />
  }, 
  cad: {
    country: 'Canada', 
    symbol: '$CAD', 
    icon: <CAD />
  },
  etc...
}

How can I write the type so that it takes a dynamic value for the key of each object – usd , or cad

I am trying to find how I can set the typescript type for for this object above so that the object names are included.

Basically want something like this:

export interface CurrencyTypes {

   [currencyName: string]: {
      country: string;
      symbol: string;
      icon: React.ReactNode; 
   }

I believe you're looking for something like this where you iterate over the values of another type.


type CountryCurrency = "usd" | "cad" | "aud";

export interface CurrencyTypes {
   [Currency in CountryCurrency]: {
      country: string;
      symbol: string;
      icon: React.ReactNode; 
   }
}

This will require that any object that implements the CurrencyTypes interface has all of the keys that are possible values of CountryCurrency

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM