DEV Community

Cover image for Generate TypeScript Declaration Files for JavaScript Files
H. Kamran
H. Kamran

Posted on • Edited on • Originally published at hkamran.com

5 4

Generate TypeScript Declaration Files for JavaScript Files

I've been moving a few utilities that I use in multiple projects to npm libraries. But I needed an easy, reliable way to generate TypeScript declarations, since I primarily use TypeScript.

  1. Open your project and ensure you have a package.json

  2. Install the typescript library as a development dependency
     

    • With pnpm: pnpm i -D typescript
    • With npm: npm i -D typescript
    • With yarn: yarn add typescript -D
  3. Add JSDoc tags to your functions, variables, classes, etc.

    For example, here's a snippet from one of my utilities:

    /**
    * Apply classes that result in a true condition
    * @param {string[]} classes
    * @returns A list of classes
    *
    * @example
    * classNames("block truncate", selected ? "font-medium" : "font-normal")
    */
    export const classNames = (...classes) => {
    return classes.filter(Boolean).join(" ");
    };
    

     

  4. Add the prepare script (or whichever one you want to use) to the scripts object in package.json

    For example, mine looks like this:

    "scripts": {
    "prepare": "tsc --declaration --emitDeclarationOnly --allowJs index.js"
    },
    

     

    This command runs tsc, the TypeScript compiler, and tells it to only generate .d.ts files (declaration files). Be sure to replace index.js with your JavaScript files.

    The prepare script runs before a npm package is packed (typically with npm publish or npm pack, or the equivalents with other package managers).

  5. Run your npm script
     

    • With pnpm: pnpm prepare or pnpm run prepare
    • With npm: npm run prepare
    • With yarn: yarn run prepare

Using the classNames function above, the TypeScript compiler generated the following declaration:

export function classNames(...classes: string[]): string;
Enter fullscreen mode Exit fullscreen mode

If you have any questions, send a tweet my way. I hope that this guide comes in handy for you, thanks for reading!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay