Search code examples
typescriptimportmoduledefinitelytypedtype-definition

Typescript: To make use of some typedefs I need "import" which turns my file in an external module (unusable for me)


For a number of Typescript typedefs it seems I need to write an import statement on top of my file. But this means that my file becomes an external module (which I do not want!).

For a number of (good) reasons I don't want my file become an external module.

My question: How can I make use of such typedefs (like from 'leaflet-easybutton' in the example below) without having my .ts file turned into an external module?

Example code...

myProblem.ts

//import 'leaflet-easybutton';
//import * as L from 'leaflet';

interface SignalR {
    myHub: MyNamespace.IMyHub; // merges this member with the regular SignalR interface
}    

namespace MyNamespace {
    "use strict";
    export class MyClass {
        constructor() {
            // easyButton doesn't exist error if "import .." statements ARE commented out on top
            let btn1 = L.easyButton("fa-object-group", null, "title");

            // myHub doesn't exist error if "import .." statements ARE NOT commented out on top
            // and if I use the "import .." statements it turns my file into a module (and I don't want that)
            let client: IMyHandler = $.connection.myHub.client; 
        }
    }

    export interface IMyHub {
        client: IMyHandler;
    }

    interface IMyHandler {
        myCallback: (arg1: string, args2: number) => void;
    }
}

package.json:

{
    "_comment_": "https://www.npmjs.com/",
    "version": "1.0.0",
    "name": "asp.net",
    "private": true,
    "dependencies": {
      "jquery": "3.2.1",
      "leaflet": "1.3.0",
      "leaflet-easybutton": "2.2.4",
      "signalr": "2.2.2"
    },
    "devDependencies": {
      "@types/jquery": "3.2.18",
      "@types/leaflet": "1.2.5",
      "@types/leaflet-draw": "0.4.10",
      "@types/signalr": "2.2.35"
    }
  }

Solution

  • Ok, I think I found a solution:

    I added a file _TypeHelper.d.ts (could have any name.d.ts) to my project with the following content:

    import 'leaflet-easybutton';
    import * as _L from 'leaflet';
    
    declare global {
        const L: typeof _L;
    }
    

    As far as I understand, this does the trick of enriching L by the additions coming from leaflet-easybutton. Comments very welcome!