SolidJSS
SolidJSโ€ข3y agoโ€ข
18 replies
anthy

Is it possible to have generic children for a generic component?

I'm trying to create a type-safe form, with a generic component. I pass a generic type argument to the parent component and I want it's children to derive that generic type. Here's my attempt:

import { render } from "solid-js/web";
import { children, Component, JSX } from "solid-js";

interface MyForm {
  firstName: string;
  lastName: string;
  age: number;
}

function Input<T extends { name: string }>(props: T) {
  return <input name={props.name} />
}

function Form<T>(props: { children: Component<{ name: keyof T }>[] }) {
    // I'm a beginner, I'm not sure if I'm using this helper correctly, but let's not focus on that
    const c = children(() => props.children.map(child => child())); // child is not a function

    return (
        <form>
          {c()}
        </form>
    );
}

function Example() {
  return (
    <Form<MyForm>>
      <Input name="firstName" /> {/* OK */}
      <Input name="qwe" /> {/* error! */}
    </Form>
  );
}

render(() => <Example />, document.getElementById("app")!);


Form is a generic component that receives MyForm type parameter and should only accept such children which name props of are keys of MyForm. The above code errors out in few places. I know that traditionally children should be of type JSX.Element but Elements are not callable.

I remember having issues trying to do that in React, I'm not sure if it's possible
Was this page helpful?