0

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 Answers3

2

You are probably looking for Typescript Record utility type. It is documented here

Record is equivalent to

type Record<K extends string | number | symbol, T> = { [P in K]: T }
type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap: Record<Currencies, string> = {
  tl: "₺",
  "us-dollar": "$",
  euro: "€"
}

Note 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

type Currencies = "tl" | "us-dollar" | "euro"
const currenciesMap: Partial<Record<Currencies, string>> = {
  tl: "₺",
  "us-dollar": "$",
}
nook
  • 1,729
  • 1
  • 12
  • 34
1

You don't need to access Currencies with [string]. You should just say K in Currencies, as follows:

type Currencies = 'tl' | 'us-dollar' | 'euro';

const currenciesMap: { [K in Currencies]: string } = {
  tl: '₺',
  'us-dollar': '$',
  euro: '€',
};

wonderflame
  • 6,759
  • 1
  • 1
  • 17
0

const currencies = {
  tl: "₺",
  "us-dollar": "$",
  euro: "€"
} as const


type Currency = typeof currencies[keyof typeof currencies]


Usage

const log = (currency: Currency) => console.log(currency);
log(currencies.euro)

Or:

log("€")

More info:

What does the "as const" mean in TypeScript and what is its use case?

mahan
  • 12,366
  • 5
  • 48
  • 83
  • What is `as const` doing? –  May 15 '23 at 16:08
  • This answer doesn't really responds to the question: "I want to say that the keys of this object must be one of the values defined in the Currencies type." Here you build the type from the object – nook May 15 '23 at 16:23
  • @nook. They have written also. – mahan May 15 '23 at 16:54