20
interface Crumb {
  title: string;
  url: string;
}
interface Crumbies {
  crumbsArray: Crumb[];
}


// component
const [breadcrumbs, setBreadcrumbs] = useState<Crumbies>([]);

I'm getting an error:

TS2345: Argument of type 'never[]' is not assignable to parameter of type 'Crumbies | (() => Crumbies)'.   Type 'never[]' is not assignable to type '() => Crumbies'.     Type 'never[]' provides no match for the signature '(): Crumbies'.

How to provide a correct typings for an empty array in useState hook?

UPDATE 1

const Breadcrumbs: React.FC<Crumbies> = ({ crumbsArray }) => {}

That's why i've created another interface Crumbies to wrap Crumb. Is there a better approach to this?

1 Answer 1

42

The interface called Crumbies requires you to pass an object with a field crumbsArray:

const [breadcrumbs, setBreadcrumbs] = useState<Crumbies>({crumbsArray: []});

If you want to simply have an array of Crumb you don't need to create a new interface, you can simply do it in useState:

const [breadcrumbs, setBreadcrumbs] = useState<Crumb[]>([]);

This will initialise it with an empty array.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, with the first approach: useState<Crumbies>({crumbsArray: []}) it would be impossible to use setBreadcrumbs([]) since it would require an object, second approach works. I've created that additional interface Crumbies, because i needed to type my prop in a component, check my initial question, please.
I did. That's why I told you to use Crumb[] directly, no need to define a new interface just for an array.
Check UPDATE 1, please.
@AlexanderKim if you really really want to have a separate type for you array of Crumb you can do this: type Crumbies = Crumb[]; But, as I said, you can just use Crumb[] directly, no need to have a separate type.
If the interface Crumbies is used for the component props, and crumbsArray is just a prop on the component, then sure, Crumbies works as the interface for the main component. Then, it looks like you're destructuring - good. But then you can just type your useState with Crumb[] as tudor suggested. Crumbies is for the entire component, Crumb[] is JUST for useState.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.