alien
alien

Reputation: 859

Getting "Property 'FOO' does not exist on type" in TypeScript when adding a property after the object is declared

Getting this error in TypeScript:

error TS2339: Property 'FOO' does not exist on type '{ stuff ... 201 more ...; }'.

Constants.FOO.forEach((item) => {
          ~~~

From this situation:

// Constants.js

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

// down the line in the same file:

Constants.FOO = [
  Constants.ABC,
  Constants.WWW,
]

Then in the file importing this:

import Constants from 'Constants'

// Getting the squiggly marks here showing the above error message...
Constants.FOO.forEach((item) => {
  console.log(item)
  // 123
  // 'COM'
})

How do I resolve this situation? Can I do it without having to rewrite the implementation of Constants? Because in my case there are hundreds of instances of this error for different props on Constants that are added after the object is constructed.

Note that Constants.js is a JS file and not a TS file, ideally we don't have to convert Constants.js to TS as it would be a lot of work in our case. Hopefully there is another workaround.

Upvotes: 0

Views: 34

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

I think the easiest way to manage this would be to declare a second object, copying over the contents of Constants in addition to the new FOO property:

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

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

This way, the combined Constants object will be automatically detected by TS to have all required properties, including FOO.

Another option is to define the values beforehand:

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

Upvotes: 1

Related Questions