Say I’m trying to use the MyAwesomeLib
library in a TypeScript project. The way MyAwesomeLib
works is that you load it with a <script async>
tag, then access it from the global scope as myAwesomeLib
(or window.myAwesomeLib
).
Because my project is written in TypeScript, I’m writing a .d.ts
declaration file for the library. I’ve got something like this:
interface MyAwesomeLib {
// function declarations and whatnot here
}
declare var myAwesomeLib: MyAwesomeLib;
However, because MyAwesomeLib
is loaded with a <script>
tag, there’s a chance that my code could run before it’s loaded. If that happens, then the myAwesomeLib
global won’t be defined yet, and accessing it would throw a ReferenceError
. Therefore, I need to be sure to first check with either typeof myAwesomeLib !== 'undefined'
or window.myAwesomeLib !== undefined
.
How can I get the TypeScript compiler to require me to add that check?
Failure #1: Declare as undefined
This doesn’t work, because a variable that is not defined is not the same as one that contains undefined
.
declare var myAwesomeLib: MyAwesomeLib | undefined;
// This code is allowed, but blows up at runtime
myAwesomeLib?.doSomething();
Failure #2: Window
global
This feels closer, but makes it impossible to access myAwesomeLib
as a global.
declare global {
interface Window {
myAwesomeLib?: MyAwesomeLib;
}
}
// This code is no longer allowed
if (typeof myAwesomeLib !== 'undefined')