React useState empty array type

Viewed 13785
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 Answers

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.

Related