DEV Community

Daniel Bayerlein
Daniel Bayerlein

Posted on • Edited on

The Power of TypeScript in a plain JavaScript project

Yes, TypeScript is nice. Nevertheless, I hardly use it in projects (at the moment). But the type-checking protects against potential bugs and the code completion of your own libraries in projects is also great.

Some days ago I published the following post:

With this solution you already offer the code completion with your library. In the project itself the type-checking is still missing. Additionally it is a manual effort to write the TypeScript declaration files.

The Power of TypeScript in a plain JavaScript project

First of all we need to add the typescript package as a dev dependency.

npm install typescript --save-dev
Enter fullscreen mode Exit fullscreen mode

Now we have to initialize TypeScript. This command creates the configuration file tsconfig.json in the root folder.

npx typescript --init
Enter fullscreen mode Exit fullscreen mode

There are many configuration options (📖 Reference), but the necessary configuration is manageable.

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "declaration": true,
    "emitDeclarationOnly": true
  }
}
Enter fullscreen mode Exit fullscreen mode
  • allowJs: Allow import of JavaScript files
  • checkJs: Errors are reported in JavaScript files
  • declaration: Generate .d.ts files for every JavaScript file
  • emitDeclarationOnly: Only emit .d.ts files

Now the configuration is complete and we can run the TypeScript compiler.

npx tsc
Enter fullscreen mode Exit fullscreen mode

✨ The TypeScript declaration files (.d.ts) are now automatically generated from the JSDoc.

Time for an example

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

After the TypeScript compiler was executed (npx tsc), the following declaration file was created.

File: src/unit/index.d.ts

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

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

The Power of VS Code

When using VS Code, a type-checking is also performed using the TypeScript configuration and JSDoc in addition to the code completion.

VS Code

If you have any kind of feedback, suggestions or ideas - feel free to comment this post!

Top comments (0)