首页 > 解决方案 > TS2339:在解构可能未定义的对象时,“{}”上不存在属性高度

问题描述

我正在尝试像这样解构可选类型道具:

export interface Props {
  style: object;
}

const MyComponent: React.FC<Props> = ({ style }) => {
  const { width, height, ...newStyle } = style || {};

但我收到打字稿警告:

TS2339: Property 'width' does not exist on type '{}'.

我该如何解决这个问题?

标签: reactjstypescript

解决方案


您已声明style为 simple object,它也没有widthor height

style使用适当的类型信息进行定义。例如,如果这是styleHTML 元素的属性,则正确的类型是CSSStyleDeclaration

export interface Props {
    style: CSSStyleDeclaration;
}

const MyComponent: React.FC<Props> = ({ style }) => {
    const { width, height, ...newStyle } = style || {};
    // ...
};

操场上

但是,如果它是您自己的信息,请使用andstyle为它定义一个类型,然后使用它。widthheight


在评论中,您已经澄清您使用的是 React Native(不是浏览器上的 React),并且:

它可能没有宽度或高度,在这种情况下,我希望它们解构为未定义。

那将是:

interface Props {
    style: {
        width?: number;
        height?: number;
    }
}

...最低限度。您正在收集其他属性的事实newStyle表明您可能需要更多。您应用默认值的事实表明它style本身应该被标记为可选 ( ?)。


推荐阅读