hse
hse

Reputation: 403

Even if I specify the type when passing the setState function as props, a type error seems to occur

https://codesandbox.io/s/beautiful-ishizaka-140bq4?file=/src/App.tsx

An error occurs when sending props to the TagInput component.

SetStateAction<Props[]> can't assign string[]

In TagInput.tsx nothing error. Please Check it..

Upvotes: 0

Views: 320

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20701

You are over complicating it. You only need to pass the type of your props to your useState generic.

Instead of :

import { Dispatch, SetStateAction, useState } from "react";
import TagInput from "./TagInput";

type Props = {
  tags: string[];
  setTags: Dispatch<SetStateAction<string[]>>;
};

const App = () => {
  const [tags, setTags] = useState<SetStateAction<Props[]>>([]);
  return (
    <>
      <TagInput tags={tags} setTags={setTags} />
    </>
  );
};

export default App;

do this:

import { Dispatch, SetStateAction, useState } from "react";
import TagInput from "./TagInput";

type Props = {
  tags: string[];
  setTags: Dispatch<SetStateAction<string[]>>;
};

const App = () => {
  const [tags, setTags] = useState<string[]>([]);
  return (
    <>
      <TagInput tags={tags} setTags={setTags} />
    </>
  );
};

export default App;

The Props type is useless.

Sandbox

Upvotes: 3

Related Questions