Issue
I'm looking for any ways to restrict the props' value of child elements by the type of parent element's props in React with typescript.
type User = { name: string; age: number; };
const Parent = (props: User) => {
return (
<div>
<Child field="name" /> // ok
<Child field="age" /> // ok
<Child field="firstName" /> // not ok
</div>
);
};
I am look for something like above
Solution
I like Steve's approach, but here's an alternative (see inline comments):
// The props for `Child`
type ChildProps<FieldNames> = {
field: FieldNames;
};
// Define a generic type for the Child component.
type ChildType<FieldNames extends string> = (props: ChildProps<FieldNames>) => React.ReactElement;
// Define the component in terms of `string`
const Child: ChildType<string> = (props: ChildProps<string>) => {
return /*...*/;
};
// Define a refined child that can only use `User` names for `field`
type User = { name: string; age: number };
const ThisChild: ChildType<keyof User & string> = Child;
// Use it
const Parent = (props: User) => {
return (
<div>
<ThisChild field="name" /> // ok
<ThisChild field="age" /> // ok
<ThisChild field="firstName" /> // not ok
</div>
);
};
Answered By - T.J. Crowder
Answer Checked By - - Katrina (ReactFix Volunteer)