Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript incorrect deduces never type

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?

like image 711
echen Avatar asked Dec 02 '25 00:12

echen


1 Answers

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

like image 71
Tyler Sebastian Avatar answered Dec 03 '25 13:12

Tyler Sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!