¿Cómo creo un tipo de mecanografiado para un objeto, donde puedo tener un conjunto fijo y un conjunto dinámico de claves? Por ejemplo:
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: {}}Solución: usando un tipo de objeto mapeado :
export type item = { [key in APIMethods]?: any; } & { divId: string; role: string; };Después de jugar con el código más dentro de Visual Studio Code , el editor terminó sugiriendo usar un tipo de objeto asignado cuando había escrito esto antes
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) };