Getting TS error, "Property 'children' does not exist on type 'TPage'"

Viewed 2331

I have a component like this:

type TPage = {
  title: string;
};
const Page = React.memo(({ children, title, ...rest }: TPage) => {
  return (
    <div {...rest}>
      <div>{title}</div>
      {children}
    </div>
  );
});

And I use it as,

    <Page
      title="Title"
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "column"
      }}
    >
      <div>Some content</div>
    </Page>

This throws an error,

const Page = React.memo(({ children, title, ...rest }: TPage) => {
                           ^^^^^^^^
Property 'children' does not exist on type 'TPage'

I've tried fixing it by changing TType to,

type TPage = React.PropsWithChildren<{
  title: string;
  children: React.ReactNode;
}>;

This fixed the issue with children, but it started complaining for the style prop, saying

Property 'style' does not exist on type 'IntrinsicAttributes
  & { title: string; children: ReactNode; } & { children?: ReactNode; }'

What am I doing wrong here?

nice-browser-y7vjd

2 Answers

TS won't check what you're doing with the props (using title and children then passing the rest to a div) and won't let you use any props that aren't in the type. If you wanted to extend the functionality of the div use the JSX type in a union with your props.

type TPage = JSX.IntrinsicElements["div"] & {
  title: string;
};

As far as I know functional component in react TypeScript should look like this:

type TPage = {
  title: string;
};
const Page:FC<TPage> = React.memo(({ children, title, ...rest }) => {
  return (
    <div {...rest}>
      <div>{title}</div>
      {children}
    </div>
  );
});
//FunctionalComponent can be also insted of FC

Now after you add the FC you should get the children as a prop better to write this what. now for you style error it due to missing style prop in the type write the type like this:

 type TPage = {
      title: string;
      style: React.CSSProperties;
    };

as you can see the FC get generic type to get to props think like prop-types in react javascript but it just don't gonna let you run if you pass wrong type to a props instead of pop a console error

Related