skip to Main Content

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


  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: '€',
    };
    
    
    Login or Signup to reply.
  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": "$",
    }
    
    Login or Signup to reply.
  3. 
    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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search