4

I want to use an external library in my typescript application, but I also want to load it dynamically if it isn't loaded yet. Currently I have the following:

declare var MyLibrary:any;
export class MyLibraryService {
   getInstance () : any {
       if(MyLibrary === undefined) {
           //load the library
       } else {
           return MyLibrary;
       }
   }  
}

This throws the following error if MyLibrary doesn't exist yet.

ReferenceError: MyLibrary is not defined

Is there a way I can check if MyLibrary is defined without throwing an exception?

nicholaswmin
  • 17,508
  • 12
  • 71
  • 142
Sam
  • 1,245
  • 2
  • 10
  • 26
  • This may indeed be a duplicate, the ReferenceError exception caught me off guard and I thought it was specific to typescript, but further investigation shows it's just normal javascript behaviour – Sam Mar 05 '18 at 15:27

1 Answers1

3

Just use typeof:

console.log(typeof FooClass) // undefined
console.log(typeof FooClass === 'undefined') // true

I doubt there's any need to use language features specific to TypeScript.

nicholaswmin
  • 17,508
  • 12
  • 71
  • 142