Let's consider the following scenario:
const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const;
type MyValue = 'fish' | 'bear' | 'cow';
const myValueMap: Record<string, MyValue> = {
[myObj.foo]: 'fish',
[myObj.bar]: 'cow',
} as const;
Since myValueMap
is defined as an object with indefinite string keys, there is a lack of type-checking on the specific keys of the object (cat
and dog
). I could eliminate the explicit declaration entirely, but that would mean not ensuring that the values are MyValue
s. (In my actual project, MyValue
consists of numerous constant strings).
Is there a way, without resorting to a wrapper function, to guarantee that the values are MyValue
s while preserving the type-checking property?