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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With