【问题标题】:Why typescript reports an error "Type '{}' has no property" on JS object destructuring为什么 typescript 在 JS 对象解构上报错“Type '{}' has no property”
【发布时间】:2019-04-02 10:54:21
【问题描述】:

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

const { foo } = this.state;

导致错误

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

虽然

const foo = this.state.foo;

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

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

【问题讨论】:

标签: typescript visual-studio-code


【解决方案1】:

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

来定义用于 props 和 state 的类型
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>
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2022-12-27
    相关资源
    最近更新 更多