Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element:

export class ElementProperties {
    constructor(
        public value: string,
        public adminConsentRequired: boolean,
        public displayString?: string,
        public description?: string){}

}

Next, I'm forming an Object in the same manner as traditional Javascript:

static readonly MyObject = {
        ChildProperty1: {
            NestedPropA: new ElementProperties(
                "My value",
                true
            ),
            NestedPropB: new ElementProperties(
                "My value in B",
                false
            )
        },
        ChildProperty2: {
            ...
        }
    }

However, I encountered this error message:

Class 'ElementProperties' used before its declaration.ts(2449)

I have numerous instances where I need to initialize objects with ElementProperties and creating separate variables for each seems impractical. Any suggestions on how to address this?

Thank you.

Answer №1

I may have felt a bit foolish, but I managed to uncover the solution.

It slipped my mind that Typescript can be particular about declaration order within a file.

Interestingly, MyObject was tucked away in another class within the same file, while the ElementProperties class was declared last. Rearranging the order so that the ElementProperties class came first ultimately resolved the issue.

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

Issue with NgFor nested component not refreshing after @Input modification

When populating a component called ContactUpdatableItem within a NgFor, the code looks like this: <section class="plContactCreation-listItem" *ngFor="let contact of contacts$ | async; index as idx" > <contact-updatable-item [c ...

Creating dynamic charts in Javascript using Firebase

My dad recently asked me to enhance our motor home by integrating an Arduino with Firebase to monitor the water and propane tanks. He's hoping to be able to check tank levels from his phone so he can see when they need refilling. I've successful ...

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

Having difficulty including a new key-value pair to a JSON object while using another JSON object

Looking to merge key value pairs from one JSON object into another. I've searched through various stackoverflow threads for solutions, but haven't found one that works for my specific scenario. const primaryObject = { name: "John Doe", ag ...

One text label to display for a MultiLineString using MapLibre GL JS

I am attempting to show text labels for MultiLineString features within a geoJSON file using MapLibre GL JS. By utilizing the symbol-placement: point option, I aim to display the labels across various zoom levels rather than only when extremely close, as w ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Creating code in AngularJS

I have the following template structure: <h1 class="text-center" ng-bind-html="row.text"></h1> When the content of my row.text is a string like this: Hi your name is {{ name }} It will display as shown below: Hi your name is {{ name }} ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Verifying authentication on the server and redirecting if not authorized

I am working on my NEXTJS project and I want to implement a feature where the cookie headers (httponly) are checked and the JWT is validated server-side. In case the user is not logged in, I would like to respond with a 302 redirect to /login. I'm unc ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

Optimal Strategy: Utilizing Spring Boot for Backend Development and jQuery for Frontend Interface

I am currently tackling a project that involves a Spring Boot 2 Backend and a jQuery Frontend. The frontend communicates with the backend by sending Ajax requests to Spring REST controllers in order to interact with database entities. One of the challenge ...

How can I pass function arguments dynamically to a nested function in Node.js?

Currently using Node 6.11.0, I am attempting to accomplish the following dynamically: const parentFunc = (arg1, arg2, arg3, arg4) => { childFunc('foo', arg1, arg2, arg3, arg4); }; I have attempted this method (without success): const pare ...

Implementing dynamic display of div based on dropdown selection in typescript

A solution is needed to display or hide specific div elements based on a dropdown selection using Typescript. Sample HTML file: <select class="browser-default custom-select"> <option selected>single</option> <option value="1"> ...

I am attempting to display text in the input box on the console, but unfortunately, I am not seeing any changes in the console when typing

I have this code, but I am not getting any output when I run it: import { restaurantList } from "../config"; import { RestrauntCard } from "./Restraunt"; const Body = () => { const searchText = "KFC"; return ( <& ...

Deciphering Google location data using JavaScript

It appears that this code is not functioning properly for unknown reasons let url = "https://maps.googleapis.com/maps/api/place/search/json?"; url += "location="+lat+","+lng+"&"; url += "radius=500&"; url += "types=&"; url += "name=&"; url ...

Styling JSON data in a jQuery Mobile list display

Currently working on a jQuery Mobile application that aims to achieve a similar output as shown in this image: The HTML code responsible for generating the image is as follows: <ul data-role="listview" data-inset="true"> <li data-rol ...

Continuously update in JavaScript based on a condition, cease updating when the condition no longer

I have a scenario on my page where specific data needs to be refreshed every minute, but at the same time, the user should be able to view and edit certain modals. I want to ensure that when a modal is open, the data refreshes are paused so that the modal ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

Problem encountered when Next.js and CSRF token interact on the server

I've integrated the next-csrf library (https://github.com/j0lv3r4/next-csrf) into my next.js app to safeguard api routes. Despite following the documentation, I'm encountering a 500 error with the following message: {"message":"Si ...