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
CodePudding user response:
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>
);
};
CodePudding user response:
You will need to provide an explicit generic in that case. Is that what you are looking for?
type User = { name: string; age: number };
const Parent = (props: User) => {
return (
<div>
<Child<User> field="name" /> // ok
<Child<User> field="age" /> // ok
<Child<User> field="firstName" /> // not ok
</div>
);
};
type ChildProps<T> = {
field: keyof T;
};
const Child = <T extends unknown>(props: ChildProps<T>) => {
return null;
};