Assume we have the following data types
type ALL = 'AA' | 'BB' | 'CC';
type AA = { a: number; };
type BB = { b: string; };
type CC = { c: boolean; };
type MyArg = { type: ALL };
I attempted to create a mapping between type name
and type
as follows
type ReturnMap = {
'AA': AA;
'BB': BB;
'CC': CC;
}
There is also a function called hook
that should return an object based on the argument type
const hook = (g: MyArg) => {
const some = {};
...// some calculations here
return some as ReturnMap[g.type];
};
However, I encountered a TypeScript error on the line with the return
statement
Type 'any' cannot be used as an index type.
If I modify the return statement like this
const hook = (g: MyArg) => {
const some = {};
...// some calculations here
return some as ReturnMap[typeof g['type']];
};
The returned object type in case of
const answer = hook({ type: 'BB' });
will be AA | BB | CC
, but my intention is to get just BB
;