Rename a namespace from an external npm package in typescript

77 views Asked by At

I am working alot with the ArcGIS JS API in typescript, using their @arcgis/core ES6 modules. In that package, they export a namespace:

// @arcgis/core/interface.d.ts

declare namespace __esri {
  // a LOT of classes, functions, properties, etc
  ...
}

In my files, I can reference things like __esri.FeatureLayerProperties, or __esri.GroupLayer, or whatever. Its silly, but I hate the namespace __esri, and I'd love to just rename it myself to esri in my own .d.ts file.

I've looked at a number of questions tangentially related to this, but nothing so specific and simple as renaming a namespace from an external npm package, without having to manually specify everything that's in the namespace. How can I do this?

1

There are 1 answers

2
Maxqueue On

Here are a few alternative approaches you might consider:

Approach 1: Import and Re-export the Namespace You can try importing the __esri namespace into your declaration file and then re-export it. However, this might not work depending on how the ArcGIS library exports its types.

// arcgis-core-augmentation.d.ts
import * as __esri from '@arcgis/core';

declare global {
  export namespace esri {
    export import FeatureLayerProperties = 
__esri.FeatureLayerProperties;
    export import GroupLayer = __esri.GroupLayer;
    // ... and so on for other types you need
  }
}

Approach 2: Global Augmentation Another way is to use global augmentation, but this requires explicitly specifying the types you want to re-export.

// arcgis-core-augmentation.d.ts
declare global {
  namespace esri {
    type FeatureLayerProperties = __esri.FeatureLayerProperties;
    type GroupLayer = __esri.GroupLayer;
    // ... and so on for other types you need
  }
}

Approach 3: Use Type Aliases in Your Code Instead of trying to rename the namespace globally, you can create type aliases in the files where you use these types.

type FeatureLayerProperties = __esri.FeatureLayerProperties;
type GroupLayer = __esri.GroupLayer;