获得;财产';FOO';“类型”上不存在;在声明对象后添加属性时在TypeScript中
在TypeScript中获取此错误:获得;财产';FOO';“类型”上不存在;在声明对象后添加属性时在TypeScript中,typescript,Typescript,在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
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.js
是一个js文件,而不是TS文件,理想情况下,我们不必将Constants.js转换为TS,因为在我们的例子中需要大量工作。希望还有另一种解决方法。我认为最简单的管理方法是声明第二个对象,除了新的FOO
属性外,还复制常量的内容:
const InitialConstants = {
ABC: 123,
WWW: 'COM',
// ...
};
// down the line in the same file:
const Constants = {
...InitialConstants,
FOO: [
InitialConstants.ABC,
InitialConstants.WWW,
],
};
这样,TS将自动检测组合的常量
对象,使其具有所有必需的属性,包括FOO
另一个选项是预先定义值:
const ABC = 123;
const WWW = 'COM';
const Constants = {
ABC,
WWW,
FOO: [ABC, WWW],
// ...
};
没有别的办法吗?我希望不必重写太多东西…因为它可能会递归,其中一件事依赖于下一件事依赖于下一件事,等等。因此我必须创建各种InitialConstantsA…B…CDE…
对象。不幸的是,这样的对象天生对TS不友好,因为它的属性不能在初始化对象时全部确定。你也可以把FOO
变成一个getter,一次初始化它,但是这有点奇怪,仍然需要一些重构。如果我是你,我会咬紧牙关,用我答案中的方法重构它