Search code examples
typescript

Using TypeScript Record to define partial list of Keys


I am trying to use a Record to map the keys of one object to a different object. I essentially want to take the CountryCode options defined by Google's libphonenumber and map them to my own formatting objects. This works:

const countryOptions: Record<CountryCode, CountryFormat> = {
  'US': {
    //... my CountryFormat object
  },
  //...
}

However, this requires me to define every key in CountryCode, like 240 countries. I am not enabling all of these countries so I would rather not define anything for them. Is it possible to define this record type in a way that is only for partial keys of CountryCode?


Solution

  • Use the Partial built-in utility type:

    const countryOptions: Partial<Record<CountryCode, CountryFormat>> = {
      'US': {
        //... my CountryFormat object
      },
      //...
    }
    

    This makes all properties optional.