Suppose you are dealing with an external API that lists all the countries of the world. As part of the information returned through the API is the name of the country in several languages. The name of the country in the specific language is defined by the key name using the abbreviation of language (e.g. {“eng”: “Kingdom of Spain”, “spa”: “Reino de España”}). So how would we define a dynamic key when using either an interface or a type in Typescript? We would do the following:
Interface
interface Languages {
[key: string] : string
}
Types
type Languages {
[key: string] : string
}
We are telling the Typescript compiler that the key is of type string and that the value of that key is also a string.