0
votes

I have a very simple TypeScript/React/TSX setup but the following piece of code shows an error:

import React from 'react';
import Layout from '../components/Layout';

export default function Index() {
    return (
        <Layout>
            <div>Hello world</div>
        </Layout>
    );
}

The <Layout [...]> tag is underlined in red, saying: Property 'children' is missing in type '{}' but required in type 'LayoutProps'.ts(2741).

Indeed, the props (LayoutProps) of the Layout component requires children:

export interface LayoutProps {
    children: React.ReactNode;
}

However, as you see in the first snippet, there is actually a child, a <div/>. I'm trying to figure out why it is not "detected" by TypeScript.

If I define the children prop as an JSX attribute, as in <Layout children={null} />, the error disappears, as if I could only define children using this syntax.

I'm using TypeScript v3.7.4 with a basic React/NextJS-friendly tsconfig.json.

2

2 Answers

0
votes

How are you typing your Layout component props? This should work without typescript errors.

Layout.tsx

import React from "react";

interface Props {
  children: React.ReactNode;
}

export const Layout = ({ children }: Props) => {
  return <div>{children}</div>;
};

Index.tsx

import React from "react";
import { Layout } from "./Layout";

export default function Index() {
  return (
    <Layout>
      <div>Hello world</div>
    </Layout>
  );
}
0
votes

I ended up using npm-update-all to ensure everything was up to date, and it fixed my problem. The project was new, so I previously assumed that npm would have installed "fresh" dependencies, but it wasn't the case by the look of things.