Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Generating API Docs with TypeDoc

Hello! In our last lesson, we configured our package.json with the modern exports and typesVersions fields, ensuring our library can be consumed correctly in various JavaScript environments. With the package structure defined, we now turn to making our library usable and understandable for other developers.

This lesson will guide you through setting up TypeDoc to automatically generate a professional API documentation website directly from your source code. We'll leverage the TSDoc comments we've been writing throughout the course to create a rich, browsable, and always-up-to-date reference for your library's API. This is a critical step in transforming a personal project into a shareable, open-source-ready library.

1. The Foundation: TSDoc and TypeDoc

Before we start installing packages, it's crucial to understand the two key components we'll be working with: TSDoc and TypeDoc. They sound similar, but they serve distinct purposes.

  • TSDoc: This is a specification for how to write documentation comments in TypeScript code. Think of it as a standardized grammar for your comments, using tags like @param and @returns. Since it's a standard, various tools, including VS Code, can understand it to provide enhanced tooltips and intellisense. You've already been using its basic principles.
  • TypeDoc: This is a tool that acts as a documentation generator. It parses your TypeScript source code, reads the type information, understands the TSDoc comments, and uses all this information to generate a static HTML website.

The article "Documenting Your TypeScript Projects" provides an excellent overview of this relationship and shows the powerful difference that well-written TSDoc comments can make.

Documenting Your TypeScript Projects: There Are Options

This article from the BitSrc blog explains why code documentation is essential and clearly differentiates between the TSDoc standard and the TypeDoc generator tool.

Please read the introduction and the sections 'Writing proper code comments' and 'TypeDoc: here to solve all your problems'. Pay attention to the 'before' and 'after' images that illustrate how TSDoc comments enrich the documentation generated by TypeDoc.

2. Setting Up TypeDoc in Your Project

Now let's integrate TypeDoc into our project. The process involves installing the tool, configuring it, and adding a script to our package.json for easy execution.

Step 1: Installation

First, we need to install TypeDoc as a development dependency.

npm install --save-dev typedoc

Step 2: Configuration

While you can pass all options to TypeDoc via the command line, it's much cleaner to use a dedicated configuration file. Create a new file named typedoc.json in the root of your project with the following content:

{
  "$schema": "https://typedoc.org/schema.json",
  "entryPoints": ["src/index.ts"],
  "out": "docs"
}

Let's break this down:

  • $schema: This provides JSON schema validation and autocompletion in VS Code, which is highly recommended.
  • entryPoints: This tells TypeDoc where to start scanning your project. Since our src/index.ts exports the entire public API of our library, it's the perfect entry point.
  • out: This specifies the directory where TypeDoc will place the generated HTML files. A docs folder is a common convention.

Step 3: Add a package.json Script

To make generating the documentation easy and repeatable, let's add a script to package.json:

// package.json
"scripts": {
  // ... your existing scripts for test, build, etc.
  "docs": "typedoc"
}

Because we created typedoc.json, running the typedoc command without any arguments will automatically pick up that configuration.

3. Authoring High-Quality Documentation with TSDoc

With the tooling in place, the quality of your documentation now depends on the quality of your TSDoc comments. Let's review the syntax and cover the most important tags for documenting a library like ours.

The following video provides a concise and practical demonstration of adding TSDoc comments and generating the documentation.

TypeDoc Crash Course - TypeScript Documentation Generator

The 'TypeDoc Crash Course' by Hong Ly Tech gives a clear, step-by-step guide to documenting code with TSDoc and generating the output.

Watch the section 'Adding TSDoc Comments' (08:42 - 12:12). Observe how standard TSDoc blocks (/** ... */) are used and how tags like @param and @returns are added to functions and classes.

A TSDoc comment block starts with /** and ends with */. Here are the key tags you'll use constantly:

  • Summary and Remarks: The first part of the comment is the summary. You can add a more detailed description after a blank line. Use the @remarks tag for even more detailed explanations.
  • @param: Describes a function or method parameter. The format is @param <name> - <description>.
  • @returns: Describes the return value of a function. The format is @returns <description>.
  • @template: Describes a generic type parameter. Since our library is heavily generic, this is essential. The format is @template <TypeName> - <description>.
  • @example: Provides a usage example. This is one of the most valuable tags for library users. You can use Markdown within the comment to create code blocks.

Let's apply this to our map operator function as an example:

/**
 * Projects each source value to a new value as specified by the projection function.
 *
 * @remarks
 * `map` is a transformation operator that applies a function to each value
 * emitted by the source Observable, and emits the result of that function.
 *
 * @example
 * ```ts
 * import { of } from './of';
 * import { map } from '../operators/map';
 *
 * of(1, 2, 3)
 *   .pipe(map(x => x * 10))
 *   .subscribe(console.log);
 *
 * // Logs:
 * // 10
 * // 20
 * // 30
 * ```
 *
 * @template T The type of the source Observable's values.
 * @template R The type of the output Observable's values.
 *
 * @param projection A function that takes a value of type `T` and returns a value of type `R`.
 * @returns An operator function that returns an Observable of values of type `R`.
 */
export function map<T, R>(projection: (value: T) => R) {
  // ... implementation
}

The @example tag with a Markdown code block is particularly powerful. TypeDoc will render this with syntax highlighting, making your documentation clear and practical.

Test your understanding!

Consider the take operator we built in Module 6. It has the signature take<T>(count: number). Write a full TSDoc comment block for this function, including a summary, an example, and descriptions for the @template, @param, and @returns tags.

Show answer

A good TSDoc comment for the take operator would look like this:

/**
 * Emits only the first `count` values emitted by the source Observable.
 *
 * @example
 * ```ts
 * import { interval } from './interval';
 * import { take } from '../operators/take';
 *
 * // Emits 0, 1, 2, 3, 4, then completes
 * interval(1000)
 *   .pipe(take(5))
 *   .subscribe(console.log);
 * ```
 *
 * @template T The type of the source Observable's values.
 *
 * @param count The maximum number of values to emit.
 * @returns An operator function that returns an Observable that emits at most `count` values.
 */
export function take<T>(count: number) {
  // ... implementation
}

4. Generating and Viewing Your Documentation Site

Now for the rewarding part. With your configuration in place and your code commented, generating the documentation is as simple as running the script we created.

  1. Run the command from your project's root directory:
    npm run docs
    
  2. Inspect the output: You'll see a new docs folder. Inside, you'll find an index.html file.
  3. View the site: Open docs/index.html in your web browser.

You will be greeted with a professional-looking documentation site. You can navigate through your modules, classes, interfaces, and functions. The types are hyperlinked, and the examples are formatted neatly.

TypeDoc Generated API Documentation Example
This image shows an example of a documentation page generated by TypeDoc. Note the clear separation of parameters, return values, and source links, all derived automatically from the code and its TSDoc comments.

To see the generation and viewing process in action, you can refer back to the "TypeDoc Crash Course" video.

TypeDoc Crash Course - TypeScript Documentation Generator

This segment of the video demonstrates the final steps: running the TypeDoc command and exploring the resulting HTML documentation.

Watch the section 'Generating and Viewing Documentation' (11:51 - 16:01). This will give you a feel for navigating the generated site and seeing how the TSDoc comments are transformed into a user-friendly format.

Conclusion

Congratulations! You have now set up a fully automated documentation pipeline for your library. By writing descriptive TSDoc comments as you code, you can generate a comprehensive and professional API reference with a single command. This not only helps others understand your work but also serves as an invaluable reference for your future self.

Key Takeaways:

  • TSDoc is the standard for comments; TypeDoc is the tool that turns them into a website.
  • A typedoc.json file is the cleanest way to configure TypeDoc for your project.
  • Using a package.json script ("docs": "typedoc") standardizes the generation process.
  • Rich TSDoc comments using tags like @param, @returns, @template, and especially @example, are the key to creating useful documentation.

Next Up:

With our library's code, tests, packaging, and documentation in place, we are ready for the final step before publishing: automating the release process. In the next lesson, we will adopt the Conventional Commits specification and use a tool like release-it to automate versioning, changelog generation, and tagging, making the process of publishing new versions of your library seamless and error-free.

Can't find a good explanation? Sign up and we'll make it for you

Sign up