Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React with Typescript: Argument of type 'never[]' is not assignable to parameter of type 'StateProperties | (() => StateProperties)'

I am practicing typescript. For the backend, I used node express typescript and for the frontend, I used react typeScript. I fetched the data from the backend and try to render it on my browser. I am getting an error: property 'name' does not exist on type 'never'. TS2339. I think this error is coming from typescript. This is the error visualization

This is my backend setup

import express = require("express");
import cors = require("cors");
const app = express();
app.use(cors());
const port = 8080;
app.get("/", (req, res) =>
  res.send([
    {
      name: "John",
      age: 36
    },
    {
      name: "alex",
      age: 27
    }
  ])
);

app.listen(port, () => console.log(`server running port ${port}`));

This is is my React component

    import React, { useEffect, useState } from "react";

interface StateProperties {
  name: string;
  age: number;
}

//StateProperties | (() => StateProperties)
function App() {
  const [state, setState] = useState<StateProperties>([]);

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const response = await fetch("http://localhost:8080/");
    const data = await response.json();
    console.log(data);
    setState(data);
  };

  return (
    <div className="App">
      {state.length}

      {state.map((list, index) => {
        return <li key={index}>{list.name}</li>;
      })}
    </div>
  );
}

export default App;
like image 492
juha Avatar asked Apr 18 '20 06:04

juha


People also ask

What is not assignable to parameter of type never error in TypeScript?

The error "Type is not assignable to type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to mutate the array. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; . Here is an example of how the error occurs. Copied!

Is not assignable to parameter of type TypeScript?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

What is never [] in React?

The type of the array is inferred to be never[] , in other words, an array that will always be empty, which is not what we want. To solve the error, use the generic on the useState hook to type the state array.

What is a never []?

TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception. Example: never.


1 Answers

You need to provide the interfaces/type aliases so that TypeScript will know the typings of state.

After creating the interface for state, you will need to provide the interface as the generics for useState.

To solve the 2nd issue, you will need to provide the key props to each item of the <li> element

interface StateProperties {
  name: string;
  age: number;
}

function App() {
  const [state, setState] = useState<StateProperties[]>([]);

  // do the rest

return (
  <div className="App">
    {state.map(({ name, age }) => {
      return <li key={`${name}-${age}`}>{name}</li>; //FROM HERE ERROR IS COMING
    })}
  </div>
  );

}
like image 71
wentjun Avatar answered Sep 21 '22 16:09

wentjun