简体   繁体   中英

Typescript await toPromise type casting error

I have following problem:

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
    }

    ...
}

I get following error during compilation:

[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'.

Im stuck here - any idea?

Here are body of used classes:

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 allow to cast json (and not only) obiects to given type including methods
     * CAUTION: Constructor of 'type' T of object obj is never call during casting
     * Example usage:
     *
     * let space: Space = this.cast(spaceFromJson,Space);
     *
     * (we use type: { new(...args): T} tp creeate fat arrow functions in prototpye...  https://stackoverflow.com/a/32186367/860099)
     *
     * @param obj object (from json) that has only fields and no methods
     * @param type desired type
     * @returns {any} object that hava fields from obj and methods from type
     */
    public static cast<T>(obj, type: { new(...args): T} ): T 
    {
        obj.__proto__ = type.prototype;
        return obj;
    }
    ...
}

I found solution:

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

So we should change building: Building to building: null as Building . Because we use "object notation" in meta field definition the mistake was that I use "non-object notation" on subfield building (in "object notation" the : change meaning from type to value definition).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM