首页 > 解决方案 > 在声明对象后添加属性时,在 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,因为在我们的情况下这将是很多工作。希望有另一种解决方法。

标签: typescript

解决方案


我认为最简单的管理方法是声明第二个对象,复制ConstantsFOO属性之外的内容:

const InitialConstants = {
    ABC: 123,
    WWW: 'COM',
    // ...
};

// down the line in the same file:
const Constants = {
    ...InitialConstants,
    FOO: [
        InitialConstants.ABC,
        InitialConstants.WWW,
    ],
};

这样,ConstantsTS 将自动检测到组合对象具有所有必需的属性,包括FOO.

另一种选择是预先定义值:

const ABC = 123;
const WWW = 'COM';
const Constants = {
    ABC,
    WWW,
    FOO: [ABC, WWW],
    // ...
};

推荐阅读