Encountering the error "TypeScript: Property 'FOO' does not exist on type" when trying to add a property to an object that has already been declared

Encountering an error in TypeScript:

error TS2339: Property 'FOO' is not found in type '{ stuff ... 201 more ...; }'.

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

Arising from this scenario:

// Constants.js

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

// further down in the same file:

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

Subsequently in the file that imports this:

import Constants from 'Constants'

// Seeing the error highlights indicating the error message above...
Constants.FOO.forEach((item) => {
  console.log(item)
  // 123
  // 'COM'
})

How can I tackle this issue? Is there a way to address it without needing to rewrite the implementation of Constants? Since in my case, there are numerous occurrences of this error for various properties on Constants that are added after the object is created.

Keep in mind that Constants.js is a JavaScript file and not a TypeScript file, so ideally avoiding the conversion of Constants.js to TypeScript would be preferable due to the extensive work involved in our situation. Is there another workaround available?

Answer №1

To effectively handle this situation, one approach could be to create a separate object by duplicating the properties of Constants and then adding the new FOO property:

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

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

By following this method, TypeScript will automatically recognize the merged Constants object with all the necessary properties, including FOO.

Alternatively, you can initialize the values beforehand like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Numerous attributes housed within a single element

In my project, I have set up a Store using Angular and NgRx 13. Within my SharedModule, I define components including selectors which load content into the store to prevent redundant API calls. https://i.stack.imgur.com/sr3nl.png This approach is impleme ...

Encountering errors in Typescript build due to issues in the node_modules directory

While running a typescript build, I encountered errors in the node_modules folder. Despite having it listed in the exclude section of my tsconfig.json file, the errors persist. What's puzzling is that another project with identical gulpfile.js, tsconf ...

Exploring the relationships between nested tuple types

When exploring the concept of mapped tuple types in TypeScript, the documentation provides an example: type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> }; type Coordinate = [number, number] type PromiseCoordinate = MapToPromise<Coor ...

Tips for navigating back to the previous component in React:

Greetings! I'm currently working on a simple CRUD example using React.Js and TypeScript. In my project, I have set up the following component hierarchy: -FetchNaselje --Modal ---AddNaselje It's structured such that AddNaselje is a child of Moda ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

The provided argument, which is of type 'RefObject<HTMLDivElement>', cannot be assigned to the parameter of type 'IDivPosition'

Currently, I am implementing Typescript with React. To organize my code, I've created a separate file for my custom function called DivPosition.tsx. In this setup, I am utilizing useRef to pass the reference of the div element to my function. However ...

Using immer JS to update a nested value has been successfully completed

What is the most efficient way to recursively change a value using a recursive function call in a Produce of Immer? The WhatsappState represents the general reducer type, with Message being the message structure for the application/db. type WhatsappState = ...

The filename is distinct from the file already included solely by the difference in capitalization. Material UI

I have recently set up a Typescript React project and incorporated Material UI packages. However, I encountered an error in VS Code when trying to import these packages - although the application still functions properly. The error message reads: File na ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

Tips for transferring items between two .ts files

Currently, in my code file numberOne.ts, I am making an API call and receiving a response. Now, I want to pass this response over to another file called numberTwo.ts. I have been attempting to figure out how to transfer the API response from numberOne.ts ...

Generating a fresh array based on the size of its existing elements is the key feature of the ForEach method

When running this forEach loop in the console, it extracts the property "monto_gasto" from an array of objects in the firebase database. Here's how it looks: something.subscribe(res => { this.ingresos = res; ...

Determine an expression based on a string in Typescript

Looking at the code snippet below, everything appears to be in order (view playground): type PathParam<T> = T extends `${string}:${infer U}` ? U : never; type Param = PathParam<"/post/:post_id">; // type Param = "post_id" ...

Managing Keyboard Input in React using TypeScript

Hey there! I'm currently working on a method that should automatically insert a specific string into a textbox when a particular key is pressed. The key in question is a non-printable character that may not be visible in most font styles, but can sti ...

Utilizing Node.js Functions for Sharing Database Queries

When it comes to sharing DB query code among multiple Node.js Express controller methods, finding the best practice can be challenging. Many samples available online don't delve deeply into this specific aspect. For instance, let's consider a ge ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...

Steps to assign a JSON file to an array within an object in Angular

What is the best way to assign a JSON file to an array within my "Client" object? I currently have a JSON file named Clients.json with the following structure: { "clients": [ { "firstName": "nameA", "lastName": "lastA", "doctorsNam ...

Unveiling the seamless integration of TypeScript with webpack/metro mainFiles module resolution

Scenario Setup In Webpack, the mainFiles module resolution feature allows for resolving specific files based on the environment. This concept is exemplified by: | Button | | - index.ts | | - index.performer.ts | | - index.customer.ts // page.ts im ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...