Muirik
Muirik

Reputation: 6289

Getting `not assignable to type 'never'` Issue in My TypeScript Function

I have a function within a React functional component that was valid syntax in vanilla JavaScript (where there weren't type definitions, of course), but I'm having issues with it in TypeScript. This is the function in question:

  const getSelection = (id: number, selection: string) => {
    setAnswers((answers) => {
      const result = [...answers];
      result[id] = selection; // The error is here
      return result;
    });
  };

This is the error:

Type 'string' is not assignable to type 'never'.ts

By the way setAnswers is where I use React's useState():

  const [answers, setAnswers] = useState([]);

It's not clear to me how to resolve this issue. I have types assigned to each parameter being passed in, but that doesn't resolve the issue. I also tried temporarily making the type for both parameters any but that also didn't resolve the issue.

Upvotes: 2

Views: 1634

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

The problem is that Typescript can't infer the type of the items in the asnwers array. This is because when you initialize state as an empty array, there are not items to infer the type from. So typescript infers the state type as never[], which isn't usable since nothing can ever be never except for never.

You can fix it by explicitly typing the call to useState with the type of that state, in this case string[].

const [answers, setAnswers] = useState<string[]>([])

Then your code works as expected.

Playground

Upvotes: 4

Related Questions