Error when casting Typescript await toPromise

I encountered the following issue:

export class FloorManagerComponent implements OnInit
{
    public meta = {
        list: [],
        building: Building,
        loading: true,
    };

    constructor(
        private router: Router, 
        private activatedRoute: ActivatedRoute, 
        private buildingService: BuildingService
    )
    {;}

    public async ngOnInit() 
    {
        let params = await this.activatedRoute.params.first().toPromise();

        this.meta.building = await this.buildingService // line 42: ERROR
            .getBuilding(params['buildingId'])          // line 42: ERROR
            .toPromise();                               // line 42: ERROR
    }

    ...
}

The error message I am receiving during compilation is as follows:

[at-loader] ./src/pages/floor/manager/floorManager.component.ts:42:9 TS2322: Type 'Building' is not assignable to type 'typeof Building'. Property 'prototype' is missing in type 'Building'.

I am currently stuck at this point - any insights?

Provided below are the details of the classes being utilized:

export class Building {

    constructor(
        public id: number,
        public name: string, 
        public image_url: string, 
    ) {}

    ...
}


export class BuildingService {

    public getBuilding(buildingId: number)
    {
        return this.http.get(Url.api('buildings/' + buildingId))
            .map( (response) => { 
                return Obj.cast(response, Building);                  
            } );
    }

    ...

}

export class Obj {

    /**
     * This method allows for casting json (and other types) objects to a specified type including methods
     * CAUTION: The constructor of 'type' T is not called during casting
     * Example usage:
     *
     * let space: Space = this.cast(spaceFromJson,Space);
     *
     * (we use type: { new(...args): T} to create fat arrow functions in prototpye...  https://stackoverflow.com/a/32186367/860099)
     *
     * @param obj object (from json) with only fields and no methods
     * @param type desired type
     * @returns {any} object that has fields from obj and methods from type
     */
    public static cast<T>(obj, type: { new(...args): T} ): T 
    {
        obj.__proto__ = type.prototype;
        return obj;
    }
    ...
}

Answer №1

I stumbled upon the solution:

public meta = {
    list: [],
    building: null as Building,
    loading: true,
};

After some consideration, it became clear that we need to modify building: Building to building: null as Building. The reason for this change is because we are using "object notation" in defining the meta field, and mistakenly used "non-object notation" for the subfield building (in "object notation", the : changes the meaning from type to value definition).

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

Is there a way to stop observing an Observable or Subject after its first emission while setting up the observer?

Currently, I am in the process of implementing dialogs using Angular 9 and I encountered a scenario where I need to unsubscribe from a Subject after its first emission. Initially, my approach was to use the take(1) or first() operators to transform the Su ...

Whenever the [required] tag switches from being true to false, it generates an event

Initially, I have set up an Angular form using the following code snippet buildForm() { this.form = this.formBuilder.group({ value1: this.formBuilder.control(null), value2: this.formBuilder.control(false) }); } The HTML contains a ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Exploring Angular 2+: Asynchronous Testing with setTimeout

I have a question regarding my testing process. I am using Angular 6, karma, and jasmine. Here is the test I have written: it(`my test`, async(() => { console.log('### start test'); fixture.detectChanges(); // calling a method wi ...

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

Retrieve information from the app-root and transfer it to the component

<body> <app-root data="myData"></app-root> </body> I have added the myData at index.html and now I want to retrieve it to use in a component. What is the best way to access this data? Thank you. ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...

Angular 7: Retrieve the most recent subscription response from an array of observables

Scenario: I am handling multiple POST requests to update a single table with diverse data sets. The response from the request will contain the updated table data. To streamline this process, I stored the observables in an array and employed forkJoin to co ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: Here's the code snippet: import React, { useState } from 'react'; import { Row, C ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

During the evaluation of an Angular application, an examination was conducted on the feature where clicking a button would increase a count and show the result in an h2 element

After clicking a button, the count is supposed to increase and the updated count should be displayed on the HTML page using Angular. I have written a test for this scenario using Jasmine + Karma runner, but the expected value is not matching. During testi ...

Expanding a class in Typescript by adding a function with the same name but varying properties and types

class A { play(a: string): string{ return a; } } class B extends A { play(c: string, b: number): string{ return c + ' ' + b.toString(); } } let x = new A(); console.log(x.play('John')); let y = new B(); console.lo ...

angular 17 standalone component utilizing ngrx-store-localstorage

In my angular 17 project, I am utilizing ngrx-store-localstorage to persist my store in localstorage using the new standalone method. Here is how I set up my meta reducer: export function localStorageSyncConfig(): LocalStorageConfig { return { keys: ...

propagate the amalgamation of tuples as an argument

I'm working with a function that returns a union type of tuples. I need to pass this return value to another function that can accept all its forms using the spread operator .... type TupleUnion = readonly [number, number] | readonly [number, number, ...

Develop a customized configuration module for managing ESLint, Prettier, and resolving import issues efficiently

Currently, I am developing a configuration npm module for my personal project. This repository includes Prettier, ESLint, tsconfig, and other tools that I have set up. You can find my configuration tools repository here: https://github.com/Seyrinian/seyri ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

How can Material UI Textfield be configured to only accept a certain time format (hh:mm:ss)?

Looking for a way to customize my material ui textfield to allow input in the format of hh:mm:ss. I want to be able to adjust the numbers for hours, minutes, and seconds while keeping the colons automatic. Any suggestions would be welcomed. ...

The fusion of Typescript with Node.js

Currently, I am delving into learning typescript and exploring how to integrate it with Node.js. After watching multiple educational videos, I came across two distinct methods for linking typescript with Node.js. The first method involves using decorators, ...