1

I would like to build nice UI API as compound component but strictly accept children that match my type.

I tried a lot of different things, but looks like @types/react doesn't allow it.

So here what I would like:

//app.ts
const App = () => 
 <Section>
    <div>Hello</div> <--- Compile Error 
    <Section.Title>Hello</Section.Title>
 </Section>
  1. Attempt 1:

    // ui-libs
    const Title = (props: TitleProp): SectionChildren  => {
     const c = <>{props.children}</>
     return { _type: "section-children", ...c};
    }
    
    type SectionChildren = { _type: "section-children" } & ReactElement;
    
    type SectionProps = { children: SectionChildren | SectionChildren[] }
    const Section (props: SectionProps) => <>{props.children}</>
    
    Section.Title = Title
    
    export default Section
    

    Error on <Section.Title>{...}:

    Type 'Element' is not assignable to type 'SectionChildrenProps'.
      Property '_type' is missing in type 'Element' but required in type '{ _type: "section-children"; }'.ts(2322)
    
  2. Attempt 2:

    // ui-libs
    const Title = (props: TitleProp): SectionChildren  => {
     const c = <>{props.children}</>
     return { _type: "section-children", ...c};
    }
    
    type SectionChildren = ReactElement<{ _type: 'b' }> | ReactElement<{ _type: 'b' }>[];
    
    type SectionProps = { children: SectionChildren | SectionChildren[] }
    const Section (props: SectionProps) => <>{props.children}</>
    
    Section.Title = Title
    
    export default Section
    

    No errors but doesn't do what I want.

I am pretty sure with the current state of @types/react we can't do what I want because of some type it's like <p = any> and stuff like that.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • The native div tag doesn't have your _type property so it can't be be a Section child element. Also your Title isn't a valid React component, an error you haven't hit yet because of the one you asked about. – Jared Smith Aug 22 '23 at 19:33
  • Does this answer your question? [Can I type React Children using Typescript?](https://stackoverflow.com/questions/70304485/can-i-type-react-children-using-typescript) – Jared Smith Aug 22 '23 at 19:34
  • Or [this](https://stackoverflow.com/questions/57627929/only-allow-specific-components-as-children-in-react-and-typescript), or [this](https://stackoverflow.com/questions/62678575/react-typescript-specifically-type-props-children-to-component), or [this](https://stackoverflow.com/questions/27366077/only-allow-children-of-a-specific-type-in-a-react-component), or... – Jared Smith Aug 22 '23 at 19:34
  • Thanks Jared, I think this GitHub threads https://github.com/microsoft/TypeScript/projects/5#column-6818354 explain it correctly. It's sad after couple years, still doesn't fix – Mike Whittom Aug 23 '23 at 02:14

0 Answers0