I have the following object:
type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap = {}
I want to say that the keys of this object must be one of the values defined in the Currencies type.
So the object is going to seem as follows:
const currenciesMap = {
tl: "₺",
"us-dollar": "$",
euro: "€"
}
So typescript should only allow these keys to be defined.
How to make this type?
I thought this would work but it didn’t:
const currenciesMap: { [key: Currencies[string]]: string } = {}
Typescript shows the following error:
An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.
3
Answers
You don’t need to access
Currencies
with[string]
. You should just sayK in Currencies
, as follows:You are probably looking for Typescript
Record
utility type. It is documented hereRecord
is equivalent toNote that when declaring your variable as a record this way, you will be forced to declare all the properties possible. If you don’t want to have them all, you could wrap it around
Partial
Usage
Or:
More info:
What does the "as const" mean in TypeScript and what is its use case?