javascript - Typescript tipo: Objeto con claves estáticas/fijas y claves dinámicas
¿Cómo creo un tipo de TypeScript para un objeto, donde pueda 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: {}}
- Enlace al Playground de Typescript aquí
Respuesta #1
Solución: usando un tipo de objeto mapeado:
export type item = {
[key in APIMethods]?: any;
} & {
divId: string;
role: string;
};
Después de trastear más con el código dentro de Visual Studio Code, el editor terminó haciendo una sugerencia de usar un tipo de objeto mapeado 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)
};
