Generate TypeScript Declaration Files for JavaScript Files

Here’s the way you can generate TypeScript declaration files for your JavaScript project

H. Kamran
1 min readMay 9, 2022

Originally published on my website

The JavaScript logo with an arrow pointing towards the TypeScript logo

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 the prepare script 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.

4. Run the prepare script

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

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

--

--

H. Kamran

I am a developer experienced in Python, JavaScript, Vue.js, Swift, and Git. I write about content that I find interesting or useful to share with the world.