typescript - 在声明对象后添加属性时,在 TypeScript 中获取“类型上不存在属性'FOO'”
问题描述
在 TypeScript 中出现此错误:
error TS2339: Property 'FOO' does not exist on type '{ stuff ... 201 more ...; }'.
Constants.FOO.forEach((item) => {
~~~
从这种情况来看:
// Constants.js
const Constants = {
ABC: 123,
WWW: 'COM',
// ...
}
// down the line in the same file:
Constants.FOO = [
Constants.ABC,
Constants.WWW,
]
然后在文件中导入这个:
import Constants from 'Constants'
// Getting the squiggly marks here showing the above error message...
Constants.FOO.forEach((item) => {
console.log(item)
// 123
// 'COM'
})
我该如何解决这种情况?我可以在不必重写的实现的情况下做到这一点Constants
吗?Constants
因为在我的情况下,在构造对象后添加的不同道具有数百个此错误实例。
请注意,这Constants.js
是一个 JS 文件而不是 TS 文件,理想情况下,我们不必将 Constants.js 转换为 TS,因为在我们的情况下这将是很多工作。希望有另一种解决方法。
解决方案
我认为最简单的管理方法是声明第二个对象,复制Constants
新FOO
属性之外的内容:
const InitialConstants = {
ABC: 123,
WWW: 'COM',
// ...
};
// down the line in the same file:
const Constants = {
...InitialConstants,
FOO: [
InitialConstants.ABC,
InitialConstants.WWW,
],
};
这样,Constants
TS 将自动检测到组合对象具有所有必需的属性,包括FOO
.
另一种选择是预先定义值:
const ABC = 123;
const WWW = 'COM';
const Constants = {
ABC,
WWW,
FOO: [ABC, WWW],
// ...
};
推荐阅读
- asp.net-mvc - 如何使用微服务架构分离现有项目?
- reactjs - Puppeteer、ExpressJS、React SSR
- phonegap-plugins - 哦,天哪。您的构建失败。点击上方的“Log”按钮查看编译日志……”
- sql - 如何从具有相同销售 ID 的总和值相等的两个不同表中获取数据?
- android - 如果使用 Asynctask 将 URL 存储在 ArrayList 中,如何从服务器下载图像?
- arrays - VBA 数组可以存储单元格属性,如字体颜色或填充颜色吗?
- c# - 使用计时器来延迟方法
- android - FirebaseInstanceId:令牌检索失败:SERVICE_NOT_AVAILABLE 错误
- angular - 用户登录后和角度导航后刷新标题菜单
- python - 预测图像目录 - 使用 tf.estimators 的 Conv Nets