rony l
rony l

Reputation: 6022

Enforce property types of child components in typescript

I am trying to enforce the type of a property in a child component. I was expecting the following code to not compile due to Child's name property not being typed correctly inside Parent in the app, but it shows not compiler warning.

Is there a way to achieve the goal that if I have a <Parent<"a">> it won't allow for children with a prop name that isn't equal to "a"?

type ChildProps<T> = {
  name: T;
};

type parentProps<T extends string> = {
  children: React.ReactElement<ChildProps<T>>;
};

function Parent<T extends string>({ children }: parentProps<T>) {
  return <div>{children}</div>;
}

function Child({ name }: ChildProps<"b">) {
  return <div>{name}</div>;
}

function App() {
  return (
    <Parent<"a">>
      <Child name="b" />
    </Parent>
  );
}

Upvotes: 3

Views: 370

Answers (1)

adsy
adsy

Reputation: 11597

You can't! And it's one of the frustrating open issues TS has. Please see this issue.

Upvotes: 1

Related Questions