-->

Error “Cannot use 'new' with an expression

2019-07-09 03:30发布

问题:

I feel like there is something really simple that I am missing here. I've got a class that I am building out that uses Esri ArcGIS API, but when I import the type definitions from the arcgis-js-api's d.ts file, I get the typescript error "Cannot use 'new' with an expression whose type lacks a call or construct signature."

Ex:

import * as IMap from 'esri/Map';

export class Foo {
    bar: (Map: IMap) {
        const map = new Map(); // <-- error here
    }
}

relevant snippets from the d.ts file:

declare namespace __esri {
    /* snip */
    interface Map extends Accessor, LayersMixin {
        allLayers: Collection;
        basemap: Basemap;
        ground: Ground;
    }

    interface MapConstructor {
        new(properties?: MapProperties): Map;
    }

    export const Map: MapConstructor;
    /* snip */
}

declare module "esri/Map" {
    import Map = __esri.Map;
    export = Map;
}

Looks like the type definition is correct to me, so what am I doing wrong that would make Typescript think that the IMap type doesn't have a constructor?

回答1:

The Map in your parameter is an instance of the IMap type. If you wanted to type it as the constructor instead, type it as typeof IMap:

bar (Map: typeof IMap) {
    const map = new Map(); 
}