【发布时间】:2020-06-29 20:56:57
【问题描述】:
问题示例。我有一个采用以下道具的组件:
interface OwnProps {
text: string;
tKey: string;
color: string;
height: number;
}
我希望组件接受这些道具,但强制您只能传入 text 道具或 tKey 道具,但不能同时传入两者。所以我是这样写的:
interface Props {
text: string;
tKey: string;
color: string;
height: number;
}
type OwnProps = Omit<Props, 'text'> | Omit<Props, 'tKey'>;
const Component = ({text, tKey, color, height}: Props) {
....
}
OwnProps 类型似乎是正确的。但是,当我解构道具打字稿时,在组件内会引发 ts-2339 错误。当我使用以下界面进行类似设置时:
interface BaseProps {
color: string;
height: number;
}
interface PropsText extends BaseProps {
text: string;
tKey?: never;
}
interface PropsTKey extends BaseProps {
tKey: string;
text?: never;
}
Typescript 很好。我想知道是否有关于省略的东西,或者打字稿不满意的类型。理想情况下,找到一个可以使用 Omit 的解决方案会很棒。
提前感谢您的帮助。
【问题讨论】:
标签: javascript reactjs typescript