3

I'm trying to figure out how to use typings files in my Angular project. But all guides or SO posts seems to tell just to import the declared module in the typings file. In my case (gridstack.js) it has no declared modules, only interfaces and one declared namespace.

I have declared gridstack in the tsconfig.file under types. And I can e.g. declare a variable of type IGridstackOptions with no compiler errors, but I get a runtime error telling me C:/myPath/src/app/other-route/other-route.component.ts (16,60): Cannot find name 'IGridstackOptions'.

Does anybody know what I'm doing wrong? And does it make sense to have a typings file without declared modules? If yes, can you explain the reasoning behind this?

Thanks :)

Beese
  • 495
  • 2
  • 5
  • 19

1 Answers1

1

You can use a library in JavaScript in two ways:

  • using library global object
  • importing library object

Up until recently most libraries predominantly used the first approach and added global objects. For example, jQuery global object. Nowadays most libraries package their libraries as UMD modules allowing the usage of the library as a global object or as imports if the code is running in a module supporting environment.

Typescript defines two ways that can be used to define declarations:

declare namespace NodeJS
declare module "buffer"

The first one defines an object (namespace, usually global), while the second defines a module. See here.

The typings file for the gridstack library defines a global object:

declare namespace GridStackUI

and this is also what is done inside the code:

(function($, _) {

    var scope = window;
    ...

    return scope.GridStackUI;
});

And it can be used in your code like this:

declare const gridstack: GridStack;

However, inside the gridstack.js there's also UMD module definition so it can be used in the module supporting environment like this:

import * as gridstack from 'gridstack';

But the typings file doesn't have a declarations for that usage.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Nice explanation @AngularInDepth ! However, the compiler tells me that GridstackUI does not exist on type window. And isn't it frowned upon, design-wise, to use window in angular, but this is maybe the only way to do it? – Beese Oct 18 '17 at 07:48
  • 1
    use the following `declare const gridstack: GridStack;`, I updated my answer – Max Koretskyi Oct 18 '17 at 08:28
  • Wonderful! Just what I needed, thank you very much, your answer is much appreciated :) – Beese Oct 18 '17 at 09:03
  • @Beese, glad I could help :) Good luck – Max Koretskyi Oct 18 '17 at 09:24