typescript - 为什么 typescript 在 JS 对象解构上报错“Type '{}' has no property”
问题描述
我在 Visual Studio Code 中对我的 JavaScript 项目启用了类型检查。尝试进行解构分配时出现错误:
const { foo } = this.state;
导致错误
[ts] 类型“{}”没有属性“foo”,也没有字符串索引签名。
尽管
const foo = this.state.foo;
工作正常,不报告任何错误。
为什么会这样?有没有办法禁用它?
解决方案
使用 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>
}
}
推荐阅读
- python - 连接一个 numpys 数组
- ngrok - HTTP 命令没有给我转发 URL
- google-cloud-platform - 文件在上传到 GCP 之前未在 terraform 中存档
- python - 列表对象没有属性拆分和许多其他错误
- dynamics-crm - XRMToolbox 无法连接到 Dynamics CRM
- json - 从 Swift 中的 String 或 TimeInterval 解码日期/时间
- amazon-web-services - 为什么 terraform 强制更换极光全球数据库?
- excel - 获取硒 VBA 的 XPATH
- javascript - 如何在 JavaScript 中使用 MDCSlider?
- sql - 在加入另一个表时更新同一列两次未按预期工作