DEV Community

Daniel Bayerlein
Daniel Bayerlein

Posted on • Edited on

4 1

How to add TypeScript Declaration Files without TypeScript

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay