首页 > 解决方案 > 使用两个 Omit<...> | 键入的 React 组件道具 省略<....> 抛出 TS 错误 2339。Pick |上不存在属性 x 挑选

问题描述

问题的例子。我有一个采用以下道具的组件:


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

打字稿很好。我想知道是否有关于省略的东西,或者打字稿不满意的类型。理想情况下,找到一个可以使用 Omit 的解决方案会很棒。

在此先感谢您的帮助。

标签: javascriptreactjstypescript

解决方案


您提供的示例不等效:

  • Omit 完全删除该属性,因此省略不同属性的类型具有不同的属性集。
  • 您的接口都具有相同的属性集。

要合并独占选项,请修改您的 OwnProps:

type OwnProps = (Omit<Props, 'text'> & {text?: never}) | (Omit<Props, 'tKey'> & {tKey?: never});

const Component = ({text, tKey, color, height}: OwnProps) => {
  // return ...
}


推荐阅读