Reputation: 632
When using a react component that passes some props to another react child component, I find myself rewriting some type definitions to the parent that was already defined in the child component.
interface ParentProps {
onChange: (value: string) => void; // I end up rewriting this, when it was already written on ChildProps interface.
}
const Parent: React.FC<ParentProps> = ({ onChange }) => {
return <Child onChange={onChange} label="Label 1" />;
};
// Child component. Could be imported from a third party library.
interface ChildProps {
onChange: (value: string) => void;
label: string;
}
const Child: React.FC<ChildProps> = ({ onChange }) => {
return <MyComponent onChange={onChange} />;
};
Are there any techniques to avoid rewriting type definitions?
Upvotes: 2
Views: 215
Reputation: 249676
Depends how much of ChildProps
you want to reuse.
If you want to reuse just a couple of properties, you can use in indexed type query to get the type of a specific property:
interface ParentProps {
onChange: ChildProps['onChange']
}
Or you can define ParentProps
to extend ChildProps
if you want to reuse all properties:
interface ParentProps extends ChildProps {
}
Or you can pick just a subset using Pick
:
interface ParentProps extends Pick<ChildProps, 'onChange'> { // Pick<ChildProps, 'onChange' | 'label'> to pick more
}
Or if you want to pick all except a subset you can use Omit
interface ParentProps extends Omit<ChildProps, 'label'> { // Omit<ChildProps, 'onChange' | 'label'> to omit more
}
Upvotes: 2