How to use interface types with new ES modules

1137
3
Jump to solution
04-22-2021 12:09 PM
RussellMGreen
New Contributor II

What is the recommended way to use interfaces when using ES modules (@arcgis/core)?

For example, I have an Angular application that I have loaded:

import GeoJSONLayer from '@arcgis/core/layers/GeoJSONLayer';
import Graphic from '@arcgis/core/Graphic'; 

How would I gain access to a type like MapViewProperties?

 

I've tried installing the @types/arcgis-js-api package in addition to @arcgis/core, but that seems like it would be overkill.

Example:

import ImageryLayer from '@arcgis/core/layers/ImageryLayer';
import GeoJSONLayer from '@arcgis/core/layers/GeoJSONLayer';
import Esri = __esri; // <--- used just for interfaces

const mapOptions: Esri.MapProperties = {...}; 

What's the recommended approach?

 

Thanks!

0 Kudos
1 Solution

Accepted Solutions
ReneRubalcava
Frequent Contributor

The @arcgis/core package already comes with the typings, no need for extra installs. You can continue to use the __esri namespace or alias it in your own d.ts file like this to use it in a short esri namespace.

View solution in original post

0 Kudos
3 Replies
ReneRubalcava
Frequent Contributor

The @arcgis/core package already comes with the typings, no need for extra installs. You can continue to use the __esri namespace or alias it in your own d.ts file like this to use it in a short esri namespace.

0 Kudos
JonathanBorgia
New Contributor

Running into the same problem. My angular app complies fine, but then breaks on loading using the
"import esri = __esri" method. @ReneRubalcava I would like to try your suggestion, but the link no longer works. 

0 Kudos
ReneRubalcava
Frequent Contributor

The import alias should still work, but might break depending on the tsconfig.

With the latest TypeScript, it's recommended that you utilize type-only imports.

import type FeatureLayer from "@arcgis/core/layers/FeatureLayer";

export function doSomethingWithLayer(layer: FeatureLayer) {
  // super cool stuff
}

 

If you want to do something like a factory method, where you want to type the properties used for something, you can do something like this.

import FeatureLayer from "@arcgis/core/layers/FeatureLayer";

type LayerFactoryProps = InstanceType<typeof FeatureLayer>;
export function layerFactory(props: LayerFactoryProps) {
  // maybe add some defaults here
  // create layer
  const layer = new FeatureLayer(props);
  return layer;
}

 

Ideally, I would recommend against using the __esri namespace, unless you really need it for things like the Event types, or watch/reactiveUtil handlers. Other than that, you should avoid it.

0 Kudos