Is there a way to restrict the values of an object map to a certain type while still being able to enumerate its keys?
Consider the following:
const obj = {
a: 'a',
b: 'b'
}
type Obj = typeof obj
const obj2: Obj
In this case, obj2 is typed with properties a
and b
.
However, if we want to restrict the properties of obj to be only strings, we can do the following:
const obj: {[name: string]: string} = {
a: 'a',
b: 'b'
}
type Obj = typeof obj
const obj2: Obj
Now, obj2 has no typed props and is limited to any indexed string property. But what if we want it to have only a
and b
props without explicitly enumerating their key types?
const obj: {[name in ('a' | 'b')]: string} = {
a: 'a',
b: 'b'
}
type Obj = typeof obj
const obj2: Obj
Is there a simpler way to achieve this?