En mi componente Product.tsx , recibo un objeto a través de una llamada API que podría tener este aspecto:
{ title: "Product 1", status: "active", tax: true, variants: [ { id: 1, sku: 'PRD1', price: 24.00, price_reduced: 19.95, size: 'M' }, { id: 2, sku: 'PRD2', price: 24.00, price_reduced: 19.95 size: 'L' }, ] } Luego presento cada variant como una fila en una tabla donde cada columna muestra el precio, el tamaño, etc. como campos de entrada editables. onChange de cada input activa updateVariant(variant.id, key, e); donde key es una de las claves de una variant y e es el evento de entrada.
updateVariant debería actualizar el valor de una variant con la key dada y se ve así:
const updateVariant = ( id: number, key: string, e: React.FormEvent<HTMLInputElement> ) => { setProduct((prevState) => { const update = { ...prevState }; const i = update.variants.findIndex((variant) => variant.id === id); const updatedVariant = update.variants[i]; updatedVariant[key] = e.currentTarget.value; // errors on this line update.variants[i] = udpatedVariant; return update; }); }; Me da un error en updatedVariant[key] = e.currentTarget.value; :
Element implicitly has 'any' type because expression of type 'string | number' can't be used to index type '{id: number, sku: string, ...}'. No index signature with a parameter of type 'string' was found on type '{id: number, sku: string ...}' Intenté cambiarlo a: updatedVariant[key as keyof typeof updatedVariant] = e.currentTarget.value; lo que me da el type 'any' is not assignable to type 'never'
Soy bastante nuevo en Typescript y perdí por completo cómo hacer que esto funcione.
EDITAR: Lo conseguí para trabajar temporalmente con
updatedVariant[key as keyof typeof updatedVariant] = e.currentTarget.value as never;¿Pero esta no puede ser la solución correcta/limpia para esto?
Lo hice funcionar declarando una interfaz así:
interface Variant { [key: string]: string | number | string[]; }y entonces
(updatedVariant as Variant)[key] = e.currentTarget.value; Mi error fue pensar que a la key le faltaba un tipo o algo así cuando, de hecho, necesitaba una interfaz para la updatedVariant .