簡體   English   中英

TypeScript 3:類型中缺少屬性

[英]TypeScript 3: property is missing in type

我正在使用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;

我收到以下錯誤:

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; }'.

我認為類型系統希望保證傳遞的值將是有效值(即“ firstName”或“ lastName”)。 我不確定要應用什么構造(以及如何應用)構造編譯器。 我想我需要提取一個接口並在兩個地方使用它:在組件中定義狀態的地方和在handleChange方法中的某個地方。

任何建議,將不勝感激。

問題是,您的狀態以打字稿yes的形式定義為具有firstnamelastname鍵的Record event.target.id是更寬泛的類型string ,盡管在您的情況下由於某種原因它被識別為number

一種方法是將其轉換為any像(修訂版):

handleChange(event) {
    this.setState({ [event.target.id]: event.target.value } as any);
}

在這種情況下,我想沒關系,因為從一開始該語句就沒有類型安全性。

我認為要獲得更可靠的類型檢查,您可以像這樣為每個輸入添加一個處理程序

function makeHandler(
    id: WhatEnumYourIdIs
): (event: React.SyntheticEvent<HTMLInputElement>) => void {
    return function(event: React.SyntheticEvent<HTMLInputElement>): void{
        this.setState({ id: target.value });
    }
}

然后添加一個處理程序

<input onChange={this.makeHandler(Enum.FirstName)} />

如果您依靠輸入ID,則不能保證state字段會匹配,它可以編譯,但實際上不會進行類型檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM