Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract types from objects

Tags:

typescript

I have a map:

const Map = {
  key1: 'value1',
  key2: 'value2'
}

I want to create a type value1 | value2 using the above object. Is it possible without repeating the values?

I tried type MyType = Map.key1 | Map.key2, but it throws the following error: Cannot find namespace 'Map'

like image 361
mohsinulhaq Avatar asked Jan 01 '23 00:01

mohsinulhaq


1 Answers

First you have to declare the MyMap variable as const.

const MyMap = {
  key1: 'value1',
  key2: 'value2'
} as const

This tells typescript that the string literals in the object should be specific constants instead just inferred as string.

Now you can get the type of that object with the typeof keyword, then index that type by it's own keys to get all possible values:

type MyMapValues = typeof MyMap[keyof typeof MyMap] // "value1" | "value2"

const a: MyMapValues = "value1"
const b: MyMapValues = "value2"

// Error: Other values not allowed:
const c: MyMapValues = "value3"

Playground

like image 164
Alex Wayne Avatar answered Jan 14 '23 05:01

Alex Wayne