Triple-Slash Directives: Compiler Hints in Comments
Triple-slash directives are compiler instructions inside comments, telling TypeScript about file dependencies. They're mostly seen in older projects or for global types, as modern `import` statements are preferred.
WHY IT EXISTS Before ES modules became the standard, TypeScript needed a way to manage dependencies between files. Triple-slash directives were created to explicitly declare that one file depended on another, allowing the compiler to process them in the correct order and create a single output file.
THE MENTAL MODEL Think of a triple-slash directive as a sticky note for the TypeScript compiler, attached to the very top of a file. These notes say, "Hey, before you compile me, you need to look at this other file first" (<reference path>) or "Make sure you know about all the types in this package" (<reference types>). They are instructions for the compiler, not part of your runtime code.
HOW IT WORKS The TypeScript compiler performs a preprocessing step before the main compilation. It scans the top of each file for these directives. A /// <reference path>... directive causes the compiler to add the referenced file to the compilation process. A /// <reference types>... directive tells the compiler to include a declaration package, similar to how import resolves modules. This process happens depth-first to build a complete list of files and types.
WHEN TO USE IT The most common modern use is /// <reference types="..." /> to make ambient type declarations available globally within a file. This is useful for environments like Node.js or test runners like Jest, where you want type checking for global variables (process, describe, it) without explicitly importing them.
WHEN NOT TO USE IT Avoid using /// <reference path="..." /> for managing dependencies in any modern TypeScript project. Use ES module syntax (import and export) instead. Path references are a sign of an outdated project structure and are less explicit and harder to maintain than modules.
ONE CANONICAL EXAMPLE In a test file, you might not import anything directly from Jest, but you still want type safety for its global functions. Adding /// <reference types="jest" /> to the top of your test file instructs TypeScript to load all of Jest's type definitions, so your calls to describe(), it(), and expect() are fully type-checked.
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.