Question
Is TypeScript comment syntax documented? In particular, does TypeScript support the C#-style /// documentation comment system, or is there another recommended way to document code?
Short Answer
TypeScript uses JavaScript's standard // and /* ... */ comments. For API documentation and editor tooltips, use JSDoc-style /** ... */ comments. A line beginning with /// has a separate, special meaning in TypeScript: it can be a triple-slash directive for compiler references, not a C# XML documentation comment.
Concept
TypeScript is a superset of JavaScript, so it keeps JavaScript's ordinary comment syntax:
// A single-line comment
/*
A comment that can span
multiple lines.
*/
For documenting functions, classes, parameters, and return values, TypeScript conventionally uses JSDoc comments. A JSDoc comment starts with /** rather than plain /*.
/** Converts a price in cents to a formatted dollar amount. */
function formatPrice(cents: number): string {
return `$${(cents / 100).toFixed(2)}`;
}
TypeScript-aware editors can display this text when a developer hovers over formatPrice or uses code completion. JSDoc comments also support tags such as @param, @returns, and @deprecated.
/// is different. TypeScript recognizes triple-slash directives in specific places, usually near the top of a file. These are compiler instructions written in an XML-like form, such as /// <reference types="node" />. They are not the C# /// XML documentation system.
In short:
- Use
//and/* ... */for normal notes. - Use
/** ... */for documentation shown by tools and editors. - Use
/// <reference ... />only when you specifically need a TypeScript triple-slash directive.
Mental Model
Think of comments as labels attached to code:
//is a sticky note for a nearby line./* ... */is a larger note that can cover several lines./** ... */is a structured label that an editor can read and show to other developers./// <reference ... />is not a label at all; it is closer to a note addressed to the TypeScript compiler saying, “consider this dependency or declaration.”
Although C# uses /// to create XML documentation, TypeScript assigns triple-slash syntax a different job. The visually similar syntax does not imply the same feature.
Syntax and Examples
Ordinary comments use JavaScript syntax:
// The maximum number of retry attempts.
const maxRetries = 3;
/*
Retry a network request after a temporary failure.
This comment may use multiple lines.
*/
function retryRequest(): void {
// Implementation goes here.
}
Use JSDoc comments to document public code:
/**
* Adds two numbers.
*
* @param left The first number.
* @param right The second number.
* @returns The sum of both numbers.
*/
function add(left: number, right: number): number {
return left + right;
}
const total = add(2, 3); // 5
The @param names should match the actual parameter names. Editors commonly show the description, parameter details, and return description while someone calls the function.
A triple-slash directive has a specialized form:
/// <reference types="node" />
console.log(process.version);
This directive asks TypeScript to include the named type declarations. In modern projects, dependencies and tsconfig.json settings usually handle this, so you should not add triple-slash directives merely as comments.
Step by Step Execution
Consider this documented function:
/**
* Returns `true` when a user is old enough to register.
* @param age The user's age in years.
* @returns Whether the age meets the minimum requirement.
*/
function canRegister(age: number): boolean {
return age >= 18;
}
const allowed = canRegister(20);
Step by step:
- TypeScript reads the
/** ... */block as a JSDoc comment associated withcanRegister. - The function declares that
agemust be anumberand that its result is aboolean. canRegister(20)calls the function withageset to20.- The expression
20 >= 18evaluates totrue. allowedreceives the valuetrue.
The JSDoc text does not change runtime behavior. Its purpose is documentation and improved editor assistance. The type annotations are checked by TypeScript during development and compilation.
Real World Use Cases
JSDoc comments are useful when code will be read or called by other people:
- Shared utility functions: Explain units, assumptions, and edge cases, such as whether a timeout is measured in milliseconds.
- Public library APIs: Describe how callers should use exported functions and classes.
- Backend services: Document required inputs, possible errors, and returned data.
- Frontend components: Explain component props, callbacks, and accessibility behavior.
- Deprecated APIs: Tell users which replacement API to adopt.
Example of communicating an important business rule:
/**
* Applies a discount percentage.
* The percentage must be between 0 and 100.
*
* @param price Original price in cents.
* @param percentage Discount percentage.
* @returns The discounted price in cents.
*/
function applyDiscount(price: number, percentage: number): number {
return Math.round(price * (1 - percentage / 100));
}
A normal // comment is often better for explaining a local implementation detail that is not part of the function's public contract.
Real Codebase Usage
In real TypeScript projects, teams usually document public boundaries rather than every obvious line of code.
A common pattern is documenting exported APIs:
/** Finds an account by its unique identifier. */
export async function findAccountById(id: string): Promise<Account | null> {
if (!id) {
return null;
}
return accountRepository.findById(id);
}
Useful documentation explains information that types alone cannot express, such as:
- Valid value ranges and units.
- Side effects, such as sending an email or updating a database.
- Security expectations, such as requiring an authenticated user.
null, empty-array, or error behavior.- Reasons for non-obvious implementation choices.
For deprecated code, use the JSDoc tag:
/**
* @deprecated Use `getUserById` instead.
*/
export function findUser(id: string): User | null {
return getUserById(id);
}
TypeScript editors can warn callers about deprecated APIs.
Triple-slash directives are mostly found in declaration files, legacy projects, or carefully controlled compiler setups. Prefer project configuration and normal ES module imports for application dependencies whenever possible.
Common Mistakes
Using /// as though it were a TypeScript documentation comment
/// Calculates the total price.
function calculateTotal(): number {
return 10;
}
This is not the standard way to create TypeScript API documentation. Use JSDoc instead:
/** Calculates the total price. */
function calculateTotal(): number {
return 10;
}
Using /* when you expect editor documentation
/* Gets the current user. */
function getCurrentUser(): User | null {
return null;
}
This is a valid regular comment, but /** ... */ is the recognized JSDoc form:
/** Gets the current user. */
function getCurrentUser(): User | null {
return null;
}
Letting comments contradict the code
/** Returns a value in seconds. */
function getTimeout(): number {
return 5_000; // Actually milliseconds.
}
Incorrect documentation can cause more damage than no documentation. Update comments when behavior changes, or make units clear in the name, such as getTimeoutMs.
Documenting what types already make obvious
/** Sets name to name. */
function setName(name: string): void {
// ...
}
Prefer useful context:
/** Updates the display name shown on the user's public profile. */
function setName(name: string): void {
// ...
}
Putting triple-slash directives in arbitrary locations
Triple-slash directives are only processed in appropriate file-level positions. Do not use them as ordinary comments inside functions or throughout application code.
Comparisons
| Form | Main purpose | Example | Typical tool support |
|---|---|---|---|
// | Short, local note | // Cache this result | Read by people |
/* ... */ | Multi-line general note | /* Explain an algorithm */ | Read by people |
/** ... */ | JSDoc API documentation | /** Gets an order. */ | Hover text, completion help, documentation tooling |
/// <reference ... /> | TypeScript compiler directive | /// <reference types="node" /> | Processed by TypeScript in supported contexts |
| TypeScript approach | C#-style equivalent idea | Important difference |
|---|---|---|
JSDoc /** ... */ | XML documentation comments | TypeScript uses JSDoc conventions, not C# XML documentation syntax. |
| Triple-slash directive | /// line prefix | In TypeScript, this is reserved for directives such as references, not ordinary API docs. |
Types and comments also have different roles:
| Feature | Answers |
|---|---|
| Type annotation | “What kind of value is this?” |
| JSDoc comment | “What does this API mean, require, or guarantee?” |
| Test | “Does the code actually behave as expected?” |
Cheat Sheet
// Single-line comment
/*
Multi-line regular comment
*/
/**
* JSDoc documentation comment.
* @param name Description of the parameter.
* @returns Description of the result.
*/
function greet(name: string): string {
return `Hello, ${name}`;
}
Common JSDoc tags:
/**
* @param value Explains an input.
* @returns Explains the returned value.
* @throws Explains a possible error.
* @deprecated Explains the replacement API.
* @example
* const message = greet("Ada");
*/
Triple-slash directive example:
/// <reference types="node" />
Rules to remember:
- Use
/**, not/*, for JSDoc. - Use types for data shapes; use JSDoc for meaning and behavior.
///is not TypeScript's equivalent of C# XML documentation comments.- Prefer modern module imports and
tsconfig.jsonconfiguration over adding reference directives casually. - Keep comments accurate, specific, and focused on non-obvious information.
FAQ
Are TypeScript comments the same as JavaScript comments?
Yes. TypeScript supports JavaScript's // and /* ... */ syntax because valid JavaScript is also valid TypeScript.
How do I write documentation comments in TypeScript?
Use a JSDoc comment beginning with /** immediately before the function, class, property, or other declaration you want to document.
Does TypeScript support C# /// XML documentation comments?
No. TypeScript does not use C# XML documentation comments as its standard API documentation format. Use JSDoc-style /** ... */ comments instead.
What does /// <reference types="..." /> mean in TypeScript?
It is a triple-slash directive. It tells TypeScript to include a particular set of type declarations, in contexts where that directive is applicable.
Will JSDoc comments appear when I hover over a function in an editor?
Usually, yes. TypeScript-aware editors such as Visual Studio Code commonly display JSDoc text in hover information and completion suggestions.
Do comments affect the JavaScript that runs?
Comments do not change program logic. Depending on compiler and build settings, comments may be preserved, removed, or transformed in generated output.
Should every TypeScript function have a JSDoc comment?
No. Document public APIs, non-obvious behavior, business rules, side effects, and edge cases. Avoid repeating information that clear names and types already communicate.
Mini Project
Description
Create a small formatting utility module that uses JSDoc to document exported functions. This mirrors a common real-world use case: a shared helper file used by multiple parts of an application.
Goal
Build documented TypeScript functions that format a person's name and calculate a final price after a percentage discount.
Requirements
Requirement 1
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Accessing Input Value from EventTarget in TypeScript
Learn why EventTarget has no value property in TypeScript and safely read values from HTML input events in Angular applications.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.