Skip to main content

TypeScript Comments

Comments are an essential part of writing clean, maintainable code. They allow you to add explanations, notes, and documentation directly within your codebase. In TypeScript, comments not only help other developers understand your code but can also provide additional type information when used with certain tools.

Introduction to TypeScript Comments

Comments in TypeScript serve several important purposes:

  • They explain complex logic or algorithms
  • They document the purpose of functions, classes, and variables
  • They temporarily disable code during debugging
  • They can provide special instructions to TypeScript and tools like JSDoc

Proper use of comments can significantly improve code readability and maintenance. Let's explore the different types of comments available in TypeScript and how to use them effectively.

Types of Comments in TypeScript

TypeScript supports three main types of comments:

  1. Single-line comments
  2. Multi-line comments
  3. JSDoc comments (for documentation)

Single-Line Comments

Single-line comments start with // and continue until the end of the line. They're perfect for brief explanations or temporary notes.

typescript
// This is a single-line comment
let counter = 0; // Initialize counter variable to zero

Multi-Line Comments

Multi-line comments start with /* and end with */. They're useful for longer explanations or when you need to comment out multiple lines of code.

typescript
/* 
This is a multi-line comment
It can span across several lines
and is useful for longer explanations
*/
function complexCalculation(x: number, y: number): number {
return x * y + Math.pow(x, 2);
}

JSDoc Comments

JSDoc comments are special multi-line comments that start with /** and end with */. They're used for formal documentation and can provide rich type information that TypeScript can leverage.

typescript
/**
* Calculates the area of a rectangle
* @param width The width of the rectangle
* @param height The height of the rectangle
* @returns The area of the rectangle
*/
function calculateRectangleArea(width: number, height: number): number {
return width * height;
}

Best Practices for Using Comments

1. Comment on Why, Not What

Your code should be clear enough to explain what it's doing. Use comments to explain why a particular approach was taken.

typescript
// BAD: Increments the counter
counter++;

// GOOD: Increment user action count to track engagement metrics
counter++;

2. Keep Comments Updated

Outdated comments are worse than no comments at all. Always update comments when you change the corresponding code.

typescript
// OUTDATED: Calculates price with 5% tax
// CURRENT CODE: Now calculates with 7% tax
function calculateTotalPrice(price: number): number {
return price * 1.07;
}

3. Use Comments for Complex Logic

Simple operations don't need comments, but complex algorithms benefit from explanations.

typescript
// Fisher-Yates shuffle algorithm to randomly reorder array elements
function shuffleArray<T>(array: T[]): T[] {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}

4. Use Comments to Disable Code During Development

Comments are useful for temporarily disabling code during testing or debugging.

typescript
function processData(data: any[]): any[] {
// Filter invalid entries
const validData = data.filter(item => item !== null);

// Apply transformation
const transformed = validData.map(item => ({
...item,
processedAt: new Date()
}));

// Debug logging
// console.log('Processed data:', transformed);

return transformed;
}

Advanced TypeScript Comment Techniques

Type Directives in Comments

TypeScript supports special comment directives that can affect how type checking works:

typescript
// @ts-ignore - Ignores the next line of code during type checking
// @ts-expect-error - Expects an error on the next line (useful for tests)
// @ts-nocheck - Disables type checking for the entire file
// @ts-check - Enables type checking in a JavaScript file

Example usage:

typescript
function example(value: string) {
// @ts-ignore
const result = value * 2; // Would normally cause a type error
return result;
}

Triple-Slash Directives

Triple-slash directives are special single-line comments that contain a single XML tag. They're used as compiler directives.

typescript
/// <reference path="..." />
/// <reference types="..." />
/// <reference lib="..." />

Example usage:

typescript
/// <reference types="node" />

// Now you can use Node.js types without explicitly importing them
const path: string = require('path').join(__dirname, 'file.txt');

Real-World Examples

Example 1: Documenting a Component in a Web Application

typescript
/**
* UserProfile Component
*
* Displays information about the currently logged-in user and allows
* for profile editing. This component handles both display and edit modes.
*
* @param user The user object containing profile information
* @param editable Whether the profile can be edited
* @returns React component
*/
interface UserProfileProps {
user: {
id: string;
name: string;
email: string;
avatarUrl?: string;
};
editable?: boolean;
}

function UserProfile({ user, editable = false }: UserProfileProps) {
// State for tracking edit mode
const [isEditing, setIsEditing] = useState(false);

// Only allow editing if the component is configured for it
const canEdit = editable && !isEditing;

// Handler for save button
const handleSave = () => {
// Implementation omitted for brevity
// ...

// Exit edit mode after saving
setIsEditing(false);
};

return (
// Component rendering code...
null
);
}

Example 2: Commenting a Complex Algorithm

typescript
/**
* Implements the Levenshtein distance algorithm to calculate the edit distance
* between two strings (how many changes needed to transform string a into b)
*
* @param a First string to compare
* @param b Second string to compare
* @returns The edit distance between the strings
*/
function levenshteinDistance(a: string, b: string): number {
// Create a matrix of size (a.length + 1) x (b.length + 1)
const distanceMatrix: number[][] = [];

// Initialize the first row of the matrix
for (let i = 0; i <= a.length; i++) {
distanceMatrix[i] = [i];
}

// Initialize the first column of the matrix
for (let j = 0; j <= b.length; j++) {
distanceMatrix[0][j] = j;
}

// Fill the matrix using the recurrence relation
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
// If characters match, cost is 0, otherwise 1
const cost = a[i - 1] === b[j - 1] ? 0 : 1;

distanceMatrix[i][j] = Math.min(
distanceMatrix[i - 1][j] + 1, // deletion
distanceMatrix[i][j - 1] + 1, // insertion
distanceMatrix[i - 1][j - 1] + cost // substitution
);
}
}

// The bottom-right cell contains the final distance
return distanceMatrix[a.length][b.length];
}

Using Comments for Documentation Generation

TypeScript's JSDoc comments can be leveraged by documentation generators like TypeDoc to create comprehensive API documentation automatically.

typescript
/**
* Represents a user in the system
* @interface User
*/
interface User {
/** Unique identifier for the user */
id: string;

/** User's full name */
name: string;

/** User's email address */
email: string;

/**
* User's role in the system
* @default "user"
*/
role?: "admin" | "user" | "guest";
}

/**
* Fetches a user by their ID
*
* @async
* @param {string} userId - The ID of the user to fetch
* @throws {Error} When user is not found
* @returns {Promise<User>} The user object
*
* @example
* ```typescript
* // Get user with ID "123"
* const user = await fetchUser("123");
* console.log(user.name);
* ```
*/
async function fetchUser(userId: string): Promise<User> {
// Implementation details...
return {
id: userId,
name: "John Doe",
email: "[email protected]"
};
}

Summary

Comments are a powerful tool in TypeScript that, when used properly, can significantly improve code quality, readability, and maintainability. Key points to remember:

  • Use single-line comments (//) for brief explanations
  • Use multi-line comments (/* */) for longer explanations
  • Use JSDoc comments (/** */) for formal documentation
  • Comment on why, not what
  • Keep comments updated when code changes
  • Use comments for complex logic, not obvious operations
  • Take advantage of TypeScript's special comment directives when needed

By following these best practices, you'll create code that's easier to understand, maintain, and collaborate on.

Exercises

  1. Take a function you've written recently and add appropriate JSDoc comments to document its parameters and return value.
  2. Find a piece of complex code in a project and improve its comments to explain the "why" behind the implementation.
  3. Use TypeScript's @ts-ignore directive to temporarily bypass a type error, and explain in a comment why it's necessary.
  4. Document an interface using JSDoc comments that explain each property's purpose and any constraints.
  5. Create a small TypeScript project that uses triple-slash directives to include external type definitions.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)