Generic Props in React and TypeScript to get rid of Children being Implicitly Any
December 22, 2023
code
error TS7031: Binding element "children" implicitly has an "any" type.
If you have ever come across the error above, it usually happens in a situation where you have a wrapper element that will have children, but you don't know all the other props it might be getting and are spreading them..
You can get rid of the error by typing the props you are spreading as generic props. Code would look like below:
code
import { ReactNode } from "react";
interface Props<T> {
props: T;
children: ReactNode;
}
export default function CardList<T>({ children, ...rest }: Props<T>) {
return <div {...rest}>{children}</div>;
}
Notes:
- The usage of
React.FCis discouraged and is officially removed from the CRA Typescript template. - With React 18,
FCno longer provideschildren, so you have to type it yourself, and you can dropFC