打字稿不正确的推论永远不会打字

ech*_*hen 3 typescript reactjs

打字稿版本:2.8.3,请考虑以下代码段

import axios from "axios";
import { Component } from "react";
import * as React from "react";

interface ICustomer {
    id: number
    firstName: string
    lastName: string
}
interface IState {
    customers: ICustomer[]
}

class AllCustomers extends Component<{}, IState> {
    public state = {
        customers: []
    }
    public componentDidMount() {
        axios.get<ICustomer[]>(`http://localhost:8080/customers`)
        .then(resp => this.setState({customers: resp.data}))
    }
    public render() {
        const {customers}  = this.state;
        return (
            <table>
                {
                    customers.map(customer => (
                        <tr key={customer.id}>
                            <td>{customer.firstName}</td>
                            <td>{customer.lastName}</td>
                        </tr>
                    ))
                }
            </table>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到编译时错误,例如customer.id不是字段类型never

不知怎的...... this.state.customer隐含的类型never[],这是错误的.如何将空数组作为初始值而不是可分配数组类型的有效实例?

Tyl*_*ian 7

这是愚蠢的,但使用ES7类属性时state,需要同时输入.

public state: IState = {
    customers: []
}
Run Code Online (Sandbox Code Playgroud)

如果你实例化state"经典"的方式

constructor(props) {
  super(props)

  this.state = { customers: [] }
}
Run Code Online (Sandbox Code Playgroud)

你不需要这个额外的步骤