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

Looking to retrieve the smallest amount of array sets in Angular4

I'm currently developing an Angular 4 application and facing an issue with a function I'm trying to write. The goal is to extract the minimum and maximum numbers from three array objects. The yAxisData object consists of three yaxis array objects ...

Is it possible to automatically set focus on the input box in an html tag multiple times instead of just once with autofocus?

Currently, I am developing an online editor that allows users to quickly edit individual words. My approach involves replacing specific words with input boxes containing the word for direct editing by users. In order to streamline the process and ensure e ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Issue encountered while retrieving data from a json server using Angular (HttpErrorResponse)

I've been working on creating a task app for practice, and my goal is to retrieve all the task data from a JSON server. However, I'm encountering an issue where the data doesn't display in the browser console as expected, and instead, an err ...

A schema already exists with the key or ID "http://json-schema.org/draft-06/schema"

While attempting to include the Material library in my Angular project using npm install --save @angular/material @angular/cdk, I encountered some issues as described in this question: Error TS2315: Type 'ElementRef' is not generic material angul ...

Execute a component method once another component has finished loading completely

My setup involves two components that are both being loaded into my <app-root> element as shown below: <app-header [calendarReference]="calendarRef"></app-header> <app-calendar #calendarRef></app-calendar> This is happening ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Creating TypeScript unit tests for nested functions: A step-by-step guide

I'm currently working with Angular 16 in combination with the ngRx framework. My development involves TypeScript coding and writing unit tests (.spec.ts) using Jasmine, especially for code similar to the example below. How do I invoke this method with ...

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

Combining attributes of objects in an array

Is the title accurate for my task? I have an array structured like this: { "someValue": 1, "moreValue": 1, "parentArray": [ { "id": "2222", "array": [ { "type": "test", "id": "ID-100" }, { ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...

The Google APIs sheet API is throwing an error message stating "Invalid grant: account not found"

I need to retrieve data from a spreadsheet using the Sheet API. After setting up a project in Google Cloud Platform and creating a service account, I granted the account permission to edit the spreadsheet. I then downloaded the credentials in JSON format. ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

Sharing information between components in Angular 2 that are not directly related as parent-child relationships

Hey there, I'm just getting started with Angular 2 and ran into a bit of a roadblock. In my homepage component, I have a ul element where I display job descriptions fetched from a Firebase API call. The data is stored in an array called "jobs" and dis ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...