Typescript version: 2.8.3, consider the following code snippet
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>
)
}
}
I get compile time errors such as customer.id is not a field on type never
Somehow ... the type of this.state.customer is implied to be never[], this is just wrong. How is an empty array as an initial value not a valid instance of the assignable array type?
It's silly, but when using ES7 class properties for state, you need to also type it.
public state: IState = {
customers: []
}
if you instantiate state the "classic" way
constructor(props) {
super(props)
this.state = { customers: [] }
}
you don't need this extra step
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With