How do I create a typescript type for an object, where I can have a fixed set and dynamic set of keys? For example:
export type APIOMethods = 'getA' | 'getB' | 'getC';
export type item = {
divId: string;
role: string;
[key: K in APIMethods]?: any;
};
// Not working โโโ ๐ด
export type item = {
divId: string;
role: string;
[key: APIMethods]: any;
};
// Not working โโโ ๐ด
// the object could look like this:
{divId: '', role: '', getA: {}} OR
{divId: '', role: '', getB: {}} OR
{divId: '', role: '', getC: {}}
Solution: using a mapped object type:
export type item = {
[key in APIMethods]?: any;
} & {
divId: string;
role: string;
};
After fiddling around with the code more inside of Visual Studio Code, the editor ended up making a suggestion to use a mapped object type when I had type this earlier
export type item = {
divId: string;
role: string;
[key: APIMethods]: any;
^๐ด An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
};