Using a third party js file with TypeScript

I'm new to typeScript and I want to be able to use a third party library that doesn't have a definition file. Does typeScript support using external libraries?

The library I am trying to use is filesaver.js https://github.com/eligrey/FileSaver.js/

Do I need to create a definition file for this library?

I just need someone to point me in the right direction.

Many thanks!

+3


source to share


3 answers


Does typescript allow external libraries?

Very easy. You just need to tell typescript about it. let's take a look at your case.

The library I am trying to use is filesaver.js

Simple only one function saveAs

. The simplest declaration:

declare var saveAs:any; 

      

and now the following will compile simply:



declare var saveAs:any; 
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

      

To write more advanced ads take a look: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/declaration%20files/Introduction.md

Note

A more accurate, but possibly overly strict example:

declare function saveAs(data:Blob , filename:string );
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

      

+9


source


Another way to call external libraries in typescript without compiling is to use the "myglobalfunction" window.

For example:

jQuery call: window["$"]
fileSaver.js : window["saveAs"](blob, "hello world.txt");

      



etc...

These calls within typescript do not generate compilation errors, but they are full-fledged ways to call the same standard functions.

+1


source


From a pragmatic, but perhaps not entirely kosher, less elegant and non-w870 approach, it will be easy to declare but not assign the variable / function you want to use with TypeScript. It doesn't give you Intellisense, but it allows you to use the library very quickly without creating any declarations or folding your own d.ts file.

For example, here's an Angular example for providing OidcTokenManager as constants in the app.core module:

((): void => {
    angular
        .module('app.core')
        .constant('OidcTokenManager', OidcTokenManager);

})();

      

This will generate TS2304. Unable to find error "OidcTokenManager" TypeScript.

However, by simply declaring the OidcTokenManager as any, TypeScript will allow you to pass:

((): void => {    
    let OidcTokenManager: any;   

    angular
        .module('app.core')
        .constant('OidcTokenManager', OidcTokenManager);

})();

      

0


source







All Articles