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

时间:2018-04-30 20:42:26

标签: reactjs typescript

Typescript version:2.8.3,请考虑以下代码片段

s.zipWithIndex2 {
    case (a, b) => (a + "2", b + 2)
}

我收到编译时错误,例如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> ) } } 不是customer.id类型的字段

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

1 个答案:

答案 0 :(得分:7)

这很愚蠢,但在为state使用ES7类属性时,您需要键入它。

public state: IState = {
    customers: []
}

如果您实例化state“经典”方式

constructor(props) {
  super(props)

  this.state = { customers: [] }
}

你不需要这个额外的步骤