1

I have a wrapper component around some child components that I want to use to manipulate their props dynamically. My issue is I want a way to get Typescript to fail to compile when the child has an invalid props type, but can't find a way to solve it. I've set up a code sandbox here and the relevant portion is in the snippet below:

const ValidChild = (props: TestProps) => (
  <span>
    Foo: {props.foo}, Bar: {props.bar}
  </span>
);

const InvalidChild = (props: OtherProps) => <span>Beep: {props.beep}</span>;

const ExtendedValidChild = (props: ExtendedTestProps) => (
  <span>
    Foo: {props.foo}, Bar: {props.bar}, Baz: {props.baz.toString()}
  </span>
);

const Wrapper = ({ children }: { children: React.ReactElement<TestProps> }) => {
  return React.cloneElement(children, { foo: "BEEP", bar: 2 });
};

const App = () => {
  return (
    <Wrapper>
      <InvalidChild beep="a" />
    </Wrapper>
  );
};

type TestProps = {
  foo: string;
  bar: number;
};

type ExtendedTestProps = {
  foo: string;
  bar: number;
  baz: boolean;
};

type OtherProps = {
  beep: "a" | "b";
};

What I would like is for typescript to compile and run when either the ValidChild or ExtendedValidChild components are provided to the Wrapper component, but fail when the InvalidChild component is supplied. I'm at a loss as to where I can go from here so any help would be most welcome.

Edit:

After further investigating it looks like this is an extant issue that others have faced as can be seen in the comments of the accepted answer of this question. I'd still like a solution if anyone can help, but it looks like it's a long standing niche issue that might not have a potential solution.

  • 1
    `InvalidChild: FC = ...`? – jonrsharpe Nov 10 '20 at 18:09
  • Does this answer your question? [Why can't TypeScript type check React props?](https://stackoverflow.com/questions/57685744/why-cant-typescript-type-check-react-props) – jonrsharpe Nov 10 '20 at 18:09
  • 1
    @jonrsharpe I'm afraid that doesn't work, typing it as `React.FC` still results in it passing type checking when passed as a child of `Wrapper`. Also the link provided also doesn't seem to work either I'm afraid. – Jake Conkerton-Darby Nov 11 '20 at 08:13

0 Answers0