Identifying JS Library Structure for TypeScript Types
To type a JS library, first identify its structure: module, global, or UMD. This dictates your .d.ts file's shape. You'll check docs for `import`/`require` or `<script>` usage. The footgun is misidentifying a UMD library, leading to incorrect import types.
WHY IT EXISTS: JavaScript libraries are packaged in many ways: ES modules, CommonJS modules, or scripts that modify the global object. To provide accurate TypeScript types, your declaration file (.d.ts) must perfectly match the library's underlying structure and how it's consumed.
THE MENTAL MODEL: Think of it as detective work. Before you can write a description of a library's API, you must first determine its module format. You investigate the code and documentation for clues like import, require, module.exports, or assignments to a global variable. This format dictates the template for your entire declaration file.
HOW IT WORKS: To identify a library's structure, analyze its usage and its code. First, check the documentation's usage examples. Do they show import, require("someLib"), or a <script> tag? Second, inspect the library's source code. Unconditional calls to require or define, or the presence of export statements, strongly suggest a modular library. In contrast, a library that assigns properties to a global object is a global library. UMD (Universal Module Definition) libraries are chameleons; their documentation might show multiple patterns, so you must check the code for logic that handles different module systems.
WHEN TO USE IT: This identification process is the mandatory first step whenever you write a declaration file for a JavaScript library that lacks one. It's fundamental to contributing to the DefinitelyTyped repository or creating types for an internal company library.
WHEN NOT TO USE IT: You can skip this investigation if a library is already written in TypeScript or ships with its own high-quality declaration files. In that case, the types are already correctly structured by the library author.
ONE CANONICAL EXAMPLE: A Node.js library like express is a clear modular library. Its documentation is built around var app = require('express')(). You would identify this as a CommonJS module and use a module-based .d.ts template. In contrast, a UMD library might show this same require syntax in its docs but also work via a <script> tag in a browser. The source notes this ambiguity, advising you to check the code itself to determine the true structure.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.