【问题标题】:React Component Props typed with two Omit<...> | Omit<....> throwing TS error 2339. Property x does not exist on Pick | Pick使用两个 Omit<...> | 键入的 React 组件道具省略<....> 抛出 TS 错误 2339。Pick |上不存在属性 x挑选
【发布时间】: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


    【解决方案1】:

    你给出的例子并不相同:

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

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

    type OwnProps = (Omit<Props, 'text'> & {text?: never}) | (Omit<Props, 'tKey'> & {tKey?: never});
    
    const Component = ({text, tKey, color, height}: OwnProps) => {
      // return ...
    }
    
    

    【讨论】:

    • 啊啊。这就说得通了。非常感谢您的回复!
    猜你喜欢
    • 2022-11-08
    • 2021-01-10
    • 2023-02-22
    • 2023-01-10
    • 2019-08-11
    • 2021-08-02
    • 2020-06-02
    • 2022-07-09
    • 2022-10-04
    相关资源
    最近更新 更多