TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸

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.FC is discouraged and is officially removed from the CRA Typescript template.
  • With React 18, FC no longer provides children, so you have to type it yourself, and you can drop FC