首页 > 解决方案 > 为什么 typescript 在 JS 对象解构上报错“Type '{}' has no property”

问题描述

我在 Visual Studio Code 中对我的 JavaScript 项目启用了类型检查。尝试进行解构分配时出现错误:

const { foo } = this.state;

导致错误

[ts] 类型“{}”没有属性“foo”,也没有字符串索引签名。

尽管

const foo = this.state.foo;

工作正常,不报告任何错误。

为什么会这样?有没有办法禁用它?

标签: typescriptvisual-studio-code

解决方案


使用 TypeScript,我们扩展了React.Component<P,S>类来创建 React 组件。您还可以通过将预期类型传递为来定义用于道具和状态的类型<P,S>

interface IProps {
    superVillian: string;
}

interface IState {
    health: string;
}

export class MyBoringComponent extends React.PureComponent<IProps, IState> {

    render() {
        const { health } = this.state;
        return <span>{`${this.props.superVillian} health is: ${this.state.health}`}</span>
    }
}

推荐阅读