Home > Net >  React Typescript No index signature with a parameter of type 'string' was found on type
React Typescript No index signature with a parameter of type 'string' was found on type

Time:05-05

I am trying to add and remove Form fields dynamically and I got stuck on assigning a value for an object property, by getting the following error on newParams[index][name] = e.currentTarget.value:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AssetParam'. No index signature with a parameter of type 'string' was found on type 'AssetParam'.

This is my code:

import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";

interface AssetParam {
    name: string,
    value: string
}

export default function NewAssetComponent() {
    const [params, setParams] = useState<AssetParam[]>([])

    const handleParamChange = (index: number, e: React.FormEvent<HTMLInputElement>) => {
        let newParams = [...params];
        const name = e.currentTarget.name;
        const param = newParams[index];
        newParams[index][name] = e.currentTarget.value;
    }

    const addParam = () => {
        setParams([...params, { name: "", value: "" }])
    }

    return (
        <>
            <div className="mt-5 container">
                <Form>
                    {params.map((param, index) => (
                        <div className="params">
                            <Form.Group className="mb-3 col-md-3" controlId="paramName">
                                <Form.Label>Name</Form.Label>
                                <Form.Control name="paramName" value={param.name || ""} type="text" placeholder="Enter Name" onChange={e => handleParamChange(index, e)} />
                            </Form.Group>

                            <Form.Group className="mb-3 col-md-3" controlId="paramValue">
                                <Form.Label>Value</Form.Label>
                                <Form.Control name="paramValue" value={param.value || ""} type="text" placeholder="Enter Value" onChange={e => handleParamChange(index, e)} />
                            </Form.Group>
                        </div>
                    ))}
                    <Button onClick={addParam}><i className="bi bi-plus-lg"></i>Add Param</Button>
                </Form>
            </div>
        </>
    )
}

How can I fix this?

CodePudding user response:

Probably the simplest is to use a cast:

newParams[index][name as keyof AssetParam] = e.currentTarget.value;

as is used to cast, or assert to TypeScript that it will be this type. You want to be able to use name to index into AssetParam so you cast it to a key of AssetParam.

  • Related