DEV Community

loading...

How to add TypeScript Declaration Files without TypeScript

danielbayerlein profile image Daniel Bayerlein Updated on ・1 min read

No code completion for your JavaScript library? No type-checking?

Declaration files are files that describe the form of an existing JavaScript codebase to TypeScript.

By using declaration files (.d.ts) you get among other things a code completion in your editor and simplify the use of the library.

But how can I create declaration files for my JavaScript library? I'll give you a short instruction.

Library function

File: src/unit/index.js

/**
  * Converts celsius (C) to fahrenheit (F)
  *
  * @param   {number} value Temperature in celsius
  * @returns {number}       Temperature in fahrenheit
  */
export const cToF = (value) => (value * 9 / 5) + 32
Enter fullscreen mode Exit fullscreen mode

Declaration file

File: src/unit/index.d.ts

export function cToF(value: number): number
Enter fullscreen mode Exit fullscreen mode

In the declaration file you describe only the parameters and the return type.

webpack configuration

The declaration files must be delivered with the library. For this I use the webpack plugin copy-webpack-plugin.

File: config/webpack/webpack.config.js

const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  ...
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.join(__dirname, '..', '..', 'src/**/*.d.ts'),
          to: path.join(__dirname, '..', '..', 'dist', '[folder].d.ts'),
          flatten: true
        }
      ]
    })
  ]
  ...
}
Enter fullscreen mode Exit fullscreen mode

Ready

With tools like dtslint you can tests declaration files for style and correctness.

The TypeScript Handbook provides detailed documentation on declaration files.

Discussion (0)

Forem Open with the Forem app