How do you write a declaration file for a library that attaches itself to the global 'window' object?
Short answer
Use a 'declare global' block (inside a module file) or a plain ambient declaration (in a non-module .d.ts) to extend the global scope's type, describing the shape the library adds to window at runtime.
Advertisement
AModel answer
Use a 'declare global' block (inside a module file) or a plain ambient declaration (in a non-module .d.ts) to extend the global scope's type, describing the shape the library adds to window at runtime.
// jquery-global.d.ts
declare global {
interface Window {
$: (selector: string) => any;
}
}
export {}; // marks this file as a module
// usage.ts
window.$('#app'); // now type-checksReal-world example
Adding types for a legacy jQuery or analytics script loaded via a <script> tag rather than an npm import.
Likely follow-ups
- Why does adding 'export {}' at the end matter for how this file is treated?
Related topics