Reactjs 重用现有类型定义的正确方法

Reactjs 重用现有类型定义的正确方法,reactjs,typescript,Reactjs,Typescript,当使用将一些道具传递给另一个react子组件的react组件时,我发现自己正在将一些类型定义重写到子组件中已经定义的父组件 interface ParentProps { onChange: (value: string) => void; // I end up rewriting this, when it was already written on ChildProps interface. } const Parent: React.FC<ParentProps&

当使用将一些道具传递给另一个react子组件的react组件时,我发现自己正在将一些类型定义重写到子组件中已经定义的父组件

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} />;
};
interface ParentProps{
onChange:(value:string)=>void;//当它已经写在ChildProps接口上时,我最终重写了它。
}
常量父项:React.FC=({onChange})=>{
返回;
};
//子组件。可以从第三方库导入。
界面小道具{
onChange:(值:string)=>void;
标签:字符串;
}
常量子项:React.FC=({onChange})=>{
返回;
};

有什么方法可以避免重写类型定义吗?

取决于要重用多少
ChildProps

如果只想重用几个属性,可以在索引类型查询中使用以获取特定属性的类型:

interface ParentProps {
    onChange: ChildProps['onChange']
}
或者,如果要重用所有属性,可以定义
ParentProps
以扩展
ChildProps

interface ParentProps extends ChildProps {
}
或者,您可以使用
pick
选择一个子集:

interface ParentProps extends Pick<ChildProps, 'onChange'>  { // Pick<ChildProps, 'onChange' | 'label'> to pick more
}
interface ParentProps extends Omit<ChildProps, 'label'>  { // Omit<ChildProps, 'onChange' | 'label'> to omit more
}