简体   繁体   中英

Property 'children' does not exist on type '{}'

I'm having a typescript error. It says that 'children' does not exist on type '{}' even though this syntax works on my other projects.

I'm guessing this new app is on React 18.

React 18 removed children from the FC type. If you want it back you need to add it to the props yourself.

const Foo: React.FC<{ children: React.ReactNode }> = ({ children }) => <>{children}</>

Or preferably, don't use the FC type at all:

interface Props {
    children: React.ReactNode
}

function Foo({ children }: Props) {
    return<>{children}</>
}

You have not defined a type for React.FC

The fix could be

type Props = {
   children: React.ReactNode
}

const Page: React.FC<Props> = ({ children }) => {
  ...
}

As mentioned by others, React 18 removed children from the props type definition.

You can do the following instead, by explicitly declaring your props should include children:

import { FunctionComponent, PropsWithChildren } from 'react';

export const MyComponent: FunctionComponent<PropsWithChildren> =
  ({ children }) => <div>{children}</div>;

The above would default the props to the unknown type.

You can also define the props:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props {
  label: string;
}

export const MyComponent: FunctionComponent<PropsWithChildren<Props>> =
  ({ label, children }) => <div>{label}: {children}</div>;

Or even better:

import { FunctionComponent, PropsWithChildren } from 'react';

interface Props extends PropsWithChildren {
  label: string;
}

export const MyComponent: FunctionComponent<Props> =
  ({ label, children }) => <div>{label}: {children}</div>;

You need to replace the destructured props argument by following

{ children }: {children: React.ReactNode}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM