I created an object containing a list of countries with their respective country codes, names, and phone codes
const CountryCodes = {
DE: {
countryCode: 'DE',
countryName: 'Deutschland',
phoneCode: 49,
},
US: {
countryCode: 'US',
countryName: 'United States',
phoneCode: 1,
},
...
}
In addition, I defined an interface for the content of this object
type CountryCode = {
countryCode: string;
countryName: string;
phoneCode: number;
};
When retrieving the keys of CountryCodes using keyof typeof CountryCodes
without specifying a type, it correctly returns 'DE' | 'US' ...
However, there is a risk of errors if no type is provided, as elements can be added or removed. To mitigate this, I decided to strictly type the CountryCodes object with the CountryCode type.
const CountryCodes: Record<string, CountryCode> = { ...
Unfortunately, after applying this type, the result of keyof typeof CountryCodes
now merely returns string
, following the definition in
Record<string, CountryCode>
Is there a way to enforce strict typing for this object while still being able to retrieve the keys of countries using keyof
?