TypeScript 3:类型中缺少属性

Ben*_*iFB 2 typescript reactjs typescript3.0

我正在使用 TypeScript 开发 ReactJS 应用程序。我使用 TypeScript 2.8 没有问题,但 2.9 和 3 给了我一个新错误。

import * as React from 'react';


class ExampleComponent extends React.Component<{}, {
        firstName: string, lastName: string
    }> {
    clearState() {
        this.setState({
            firstName: "",
            lastName: ""
        });
    }

    constructor(props) {
        super(props);
        this.state = {
            firstName: '', lastName: ''
        };

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
       //***** This is the line that gives me an error ******
        this.setState({ [event.target.id]: event.target.value });

    }
    public render() {

        return <form>

            <div className="form-group">
                <div className="row">
                    <div className="col">
                        <label className="sr-only">First Name</label>
                        <input type="text" className="form-control name-element" id="firstName"
                            placeholder="First Name" value={this.state.firstName} onChange={this.handleChange} required={true} />
                    </div>

                    <div className="col">
                        <label className="sr-only">Last Name</label>
                        <input type="text" className="form-control name-element" id="lastName"
                            placeholder="Last Name" value={this.state.lastName} onChange={this.handleChange} required={true} />
                    </div>
                </div>
            </div>

        </form>

    }
}

// Wire up the React component to the Redux store
export default ExampleComponent;
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Error   TS2345  (TS) Argument of type '{ [x: number]: any; }' is not assignable to parameter of type '{ firstName: string; lastName: string; } | ((prevState: Readonly<{ firstName: string; lastName: string; }>, props: {}) => { firstName: string; lastName: string; } | Pick<{ firstName: string; lastName: string; }, "firstName" | "lastName">) | Pick<...>'.
  Type '{ [x: number]: any; }' is not assignable to type 'Pick<{ firstName: string; lastName: string; }, "firstName" | "lastName">'.
    Property 'firstName' is missing in type '{ [x: number]: any; }'.
Run Code Online (Sandbox Code Playgroud)

我认为类型系统需要保证传递的值是有效的(即“firstName”或“lastName”)。我不确定要应用什么构造(以及如何应用它)来安抚编译器。我想我需要提取一个接口并在两个地方使用它:我在组件中定义状态的地方,以及在 handleChange 方法中的某个地方。

任何建议,将不胜感激。

Dan*_*hko 5

问题是您的状态在打字稿中被定义为Record带有键firstnamelastname. Whenevent.target.id是更广泛的 type string,尽管在您的情况下它被认为是number出于某种原因。

一种方法是将其转换为any喜欢(已更新):

handleChange(event) {
    this.setState({ [event.target.id]: event.target.value } as any);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我认为这无关紧要,因为此语句从一开始就没有类型安全性

  • ``` handleChange(event) { this.setState({ [event.target.id]: event.target.value } as any); }``` (2认同)