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?
To type the useState hook as an array of objects in React, use the hook's generic, e.g. const [employees, setEmployees] = useState< {salary: number; name: string} []> ( []). The state variable can be initialized to an empty array and will only accept objects of the specified type. Copied!
useState Hook in React. Let’s take a simple example to manage an array in the state variable. 1. Create a react application First, we’ll create a simple react application to implement the demo using create-react-app npm package. Run the following command to create a startup application.
To type the useState hook with an empty object initial value in React, use the hook's generic, e.g. const [employee, setEmployee] = useState< { [key: string]: any}> ( {}). The state variable will be typed as an object with dynamic properties and values.
The state variable can be initialized to an empty array and will only accept objects of the specified type. Copied! We used a generic to type the useState hook correctly while initializing the hook with an empty array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With