I want a similar behavior like this example, but I want to use typescript instead of Flow.
I already tried this, but the typescript doesn't show an error when I pass a wrong value:
children: React.ReactElement<Props> | React.ReactElement<Props>[];
CodePudding user response:
Use the ReactNode
type imported from React:
import type { ReactNode } from 'react';
type MyProps = {
abc: number;
children: ReactNode;
};
CodePudding user response:
This would be the idiomatic way of doing it:
import React from 'react';
import { render } from 'react-dom';
import './style.scss';
const Item = (props) => <span>Item</span>;
const Container = (props: React.PropsWithChildren<unknown>) => (
<div>{props.children}</div>
);
render(
<Container>
<Item>{/* ... */}</Item>
<span>1</span>
</Container>,
document.getElementById('root')
);
If you're looking to constrain children to be something other than ReactNode you'd need to define children as some other type. There's not enough typing in your original example to do so though (props is untyped). But This would be highly unusual and you'd need a pretty strong argument to pass something other than standard JSX Elements, and if so you may want to pass it as a prop named something other than children
e.g. of type `newPropValue: ((props: any) => JSX.Element)[]. But there are multiple component types that would satisfy that so I'd question the original rationale.