Initially, a type is established that connects enum keys with specific types:
enum MyEnum {
A,
B
}
type TypeMap = {
[MyEnum.A]:string,
[MyEnum.B]:number
}
interface ObjInterface<T extends keyof TypeMap> {
obj: T,
objData: TypeMap[T]
}
interface SecondaryInterface {
value: string,
objChosen: ObjInterface<keyof TypeMap>
}
Subsequently, an object is created where the type of objData is checked against the TypeMap:
myObj:SecondaryInterface = {value:"", objChosen:{obj:MyEnum.A, objData:"a string"}}
Although this approach partially functions, when typing objData, it displays a union type hint 'string | number' instead of just 'string' because it deduces the type based on keyof TypeMap rather than the exact TypeMap[T].
Is there a way to achieve an exact type match for the enum key used and its corresponding type defined in the type map?
While a type assertion can make it work, is there a way to achieve this without one?:
myObj:SecondaryInterface = {value:"", objChosen:<ObjInterface<MyEnum.A>>{obj:MyEnum.A, objData:"a string"}}