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>
);
}
CodePudding user response:
You can't! And it's one of the frustrating open issues TS has. Please see this issue.