zkwsk
zkwsk

Reputation: 2116

Typescript creating a type with keys based on union type

I have a translation object that can have keys corresponding to all of the languages a string might be translated in and the values being the translated strings, like so:

const trans = {
  en: "Hello, how is it going?",
  de: "Hallo, wie gehts?",
  da: "Hej, hvordan går det?"
}

I am currently typing the object like so:

type TransType = {
  [key: string]: string;
}

But I also have a union type used in other places to control what languages can be implemented:

type Languages = "en" | "de" | "da";

How can I bring these two together and control what keys can be used in the trans object based on the Languages union type?

Upvotes: 0

Views: 171

Answers (1)

Oblosys
Oblosys

Reputation: 15096

You can use a mapped type for this (docs):

type Languages = "en" | "de" | "da"

type TransType = {
  [key in Languages]: string
}
// infers TransType = { en: string, de: string, da: string }

const trans: TransType = {
  en: "Hello, how is it going?",
  de: "Hallo, wie gehts?",
  da: "Hej, hvordan går det?",
  nl: "Onbekende taal" // Error, as 'nl' is not in Languages
}

Or, as rshepp mentioned, you can use the Record utility type (docs, src), which will define the same mapped type:

type TransType = Record<Languages, string>

TypeScript playground

Upvotes: 1

Related Questions