-
Notifications
You must be signed in to change notification settings - Fork 47.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: Constraining children to type has no effect #27545
Comments
@eps1lon Remind me if this is a limitation of core TypeScript? |
import React, { ReactElement, ReactNode } from "react"; type ValidChild = ReactElement<{ customProp: string }>; type ParentProps = { const Parent: React.FC = ({ children }) => { const invalidChildren = children.filter( if (invalidChildren.length > 0) { return {children} ;}; type ChildProps = { const ChildComponent: React.FC = ({ customProp }) => { {customProp} ;}; export default function App() { Parent should complain ); } |
Bug: Constraining children to type has no effect facebook#27545
I was thinking about this approach, but this is would loop (filter) children in runtime instead of using typescript. |
What about using this approach ?? This approach allows you to catch errors at compile time and ensures that the child components adhere to the expected props and structure. import React, { ReactElement, ReactNode } from "react"; type ChildProps = { type ChildComponentProps = { const ChildComponent: React.FC = ({ customProp }) => { {customProp} ;}; const Parent: React.FC = ({ children, customProp }) => { {customProp} {children} ); }; export default function App() { |
It's a TypeScript limitation because But this shifts the burden to component consumers which defeats the purpose. Closing in favor of microsoft/TypeScript#14729 |
I need to set a constraint on parent component, so only children of certain type are allowed. Maybe this is intended behavior, but if so how do you set constraint?
React version: 18.2.0
Steps To Reproduce
to constrain what children are allowed to be passed
Link to code example: https://codesandbox.io/s/react-typescript-forked-wzkkvl?file=/src/App.tsx
The current behavior
Allows the children of parent to be of any type
The expected behavior
Parent component should be marked with error "Types of property 'children' are incompatible." if other component is passed as child
The text was updated successfully, but these errors were encountered: