React Typescript 在类型上找不到参数类型为 'string' 的索引签名

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

我正在尝试动态添加和删除表单字段,但由于在 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'.

这是我的代码:

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>
        </>
    )
}

我该如何解决这个问题?

可能最简单的是使用强制转换:

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

as 用于向 TypeScript 强制转换或断言它将是这种类型。您希望能够使用 name 索引到 AssetParam,因此您将其转换为 AssetParam.

的键