TypeScript Triple-Slash Directives
Triple-slash directives are single-line comments containing a single XML tag. The contents of the comment are used as compiler directives. They are a legacy feature from the early days of TypeScript but are still used in specific scenarios, particularly within declaration files (.d.ts).
1. Rules
- They must appear at the top of the file.
- They can only be preceded by single or multi-line comments.
- If they appear after a statement or declaration, they are treated as regular comments and ignored.
2. /// <reference path="..." />
This directive is used to declare a dependency between files. It instructs the compiler to include the referenced file in the compilation process.
/// <reference path="Validation.ts" />
/// <reference path="EmailValidator.ts" />
Use Case:
- Primarily used when working with Namespaces (internal modules) where you don't use
import/export. - Used to manually order output files when using the
--outFilecompiler option.
3. /// <reference types="..." />
This directive declares a dependency on a package (specifically @types packages). It is similar to doing import but for global types.
/// <reference types="node" />
/// <reference types="jest" />
Use Case:
- Used in declaration files (
.d.ts) to indicate that this file depends on types from another package (e.g.,node), but you don't want to use a top-levelimport(which would turn the file into a module). - Useful if you need global types (like
processordescribe) available in a file that is otherwise a module.
4. /// <reference lib="..." />
This directive allows a file to explicitly include an existing built-in lib file.
/// <reference lib="es2017.string" />
Use Case:
- Useful if your project targets an older version of JavaScript (e.g., ES5) in
tsconfig.json, but you are writing a polyfill or a specific script that relies on newer features (likees2017string methods) and you want the type checking to pass just for that file.
5. /// <amd-module />
Used to pass the name of the module to the compiler when targeting AMD (Asynchronous Module Definition).
/// <amd-module name="NamedModule" />
export class C { }
Summary: Modern vs. Legacy
- Modern Projects: You should almost always use ES Modules (
import/export). You rarely need triple-slash directives in source code (.tsfiles). - Declaration Files: You will frequently see them in
.d.tsfiles to manage dependencies between type definitions without affecting the runtime module structure.
programming/javascript/typescript/typescript programming/javascript/typescript/modules-and-namespaces