Building asynchronous constructors in Typescript

I encountered an issue in one of my TypeScript files where I have 2 classes, each with a constructor. Inside each class, it needs to obtain an instance of the other class. Here is the code snippet:

namespace pxsim {
    export class Board extends pxsim.BaseBoard {
        public tMap: trafficMap = new trafficMap();
        public x: number;
        public y: number;
        constructor(){
            this.y = 10;
            this.x = this.tMap.x;
        }
    }

    export class trafficMap{
        public b: Board = new Board();
        public y: number;
        public x: number;
        constructor(){
            this.x = 20;
            this.y = this.b.y;
        }
    }
}

Upon running the code in the browser, I encountered an error message stating

"trafficMap is not a constructor"
. It seems that the issue arises because in the Board class, when attempting to create an instance of trafficMap, the content of the latter has not been loaded yet. This leads me to believe that asynchronous constructors might be needed. Please let me know if there are any corrections to be made.

Answer №1

It seems like async constructors could be a solution to the issue I'm facing. Feel free to correct me if I'm mistaken.

Unfortunately, async constructors do not exist in this context.

Solution

When dealing with two classes that have dependencies on each other, it's helpful to consider introducing a third orchestrator class. This orchestrator class will handle the interactions between the two existing independent classes.

  • Quick Fix: Combine features of all three classes into one.
  • Better Approach: Separate the features into three distinct classes as needed.

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

Leveraging TypeScript to sort and extract specific elements from two arrays

Given two arrays, I am looking to identify the elements in array2 that match elements in array1 based on a specific property. The arrays are structured as follows: var array1 = [ {"myId": 1, "text": "a"}, {"myId& ...

The failure to build was due to the absence of the export of ParsedQs from express-serve-static-core

Encountered the error message [@types/express]-Type 'P' is not assignable to type 'ParamsArray'. Resolved it by installing specific packages "@types/express": "^4.17.8", "@types/express-serve-static-core": ...

"The process of logging in to Facebook on Ionic app speeds up by bypassing

I'm facing a minor issue with Facebook login in Ionic. I've tried using Async - Await and various other methods to make it wait for the response, but nothing seems to work. The login function is working fine, but it's not pausing for me to p ...

There was a TypeError encountered when trying to access the property 'Symbol(Symbol.iterator)' of an undefined variable

Whenever a web service request fails, this exception is thrown: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined Specifically, the HTTP GET request returns a 400 Bad Request error. Below is the component involved in this ...

Is it possible to extract TypeScript types from one interface in order to integrate them into another separate interface?

Having a TypeScript interface defined as follows: interface SampleShape { prop1?: string; prop2?: string; } Additionally, I have another separate interface in mind to utilize: interface Payload { model: { name?: string; prop1?: ...

Having trouble locating variables in VueJS3 when using Axios and TypeScript?

I am facing an issue where I am unable to access the this.somethingHere variables inside methods using axios in combination with vuejs3 and TypeScript. Template code (not required): <template> <div> <form> <label for=" ...

Traverse the elements of a BehaviorSubject named Layer_Template

I am currently facing an issue with displaying data from my BehaviorSubject. I have come across a way to iterate through a BehaviorSubject using asyncpipe which subscribes to the Observable SERVICE todo.service.ts @Injectable() export class TodoService ...

Enumerated types in Typescript: access the values

Below is a flagged enum I have: enum PermissionEnum { SU = 1 << 0, // 1 Administrator = 1 << 1, // 2 User = 1 << 2 // 4 } If the value given is 6, how can I achieve: An array of strings -> ['Adm ...

Strategies for ensuring that code does not execute in Angular until the API response has been received

Currently, I am facing an issue where I need to wait for data from an API in order to set the value of a variable and use it in an if condition. The problem lies in my uncertainty about how to properly handle this asynchronous task using async and await. ...

The button is obscured by the dropdown menu

Here is the code snippet I am working with: HTML <nav class="navbar bg-dark navbar-dark"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class=&quo ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

Receiving no information from NSURLRequest (asynchronously) from a php/json service

I am encountering an issue while trying to fetch data from a website to my iOS device. The website utilizes a PHP file to extract data from a MySQL database and then sends it back in JSON format. Here is the code snippet I am using to retrieve the data. T ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Error encountered while attempting to globally install TypeScript using npm: "npm ERR! code -13"

Issue with npm error 13 Having trouble installing typescript-g package Error details: - errno: -13, - npm ERR! code: 'EACCES', - npm ERR! syscall: 'symlink', - npm ERR! path: '../lib/node_modules/typescript/bin/tsc', ...

Compilation of Zod record with predefined keys

I need to create a dictionary similar to a zod schema for an object with multiple keys that are already defined elsewhere, all sharing the same value type. Additionally, all keys must be required. const KeysSchema = z.enum(['a', 'b', &a ...

Make sure that a lengthy task is initiated only once, and any additional requests are queued with only a single entry in the queue

My program has a compute-intensive method called Calculate that can take a few seconds to run, and requests for this method can come from multiple threads simultaneously. I need to ensure that only one instance of Calculate is executing at a time, and any ...

Improve disorganized subscription processes to enhance future subscriptions

While diving into my Angular learning journey, I stumbled upon Observables which intrigue me but still hold a mystery for me. One specific challenge I faced was having an Observable that depended on another Observable to complete before proceeding. This l ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

The narrowing of Union types in Typescript is not possible when it is based on

I'm facing an issue with narrowing down a union type in typescript. Let's say we have two interfaces and a union: interface A { flag: true callback: (arg: string) => void } interface B { flag?: false callback: (arg: number) = ...