1

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

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} />;
};

是否有任何技术可以避免重写类型定义?

4

1 回答 1

2

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
}

或者,如果您想选择除子集之外的所有内容,您可以使用Omit

interface ParentProps extends Omit<ChildProps, 'label'>  { // Omit<ChildProps, 'onChange' | 'label'> to omit more
}
于 2019-08-19T07:51:24.597 回答