Darek Kay's picture
Darek Kay
Solving web mysteries

Import TypeScript types in JavaScript projects

Let's assume we want to write a Jest config object. Our IDE cannot infer available Jest options:

Editor autocomplete with generic suggestions

With JSDoc comments, it's possible to document our JavaScript objects and function parameters. While JSDoc is mostly a documentation tool, editors like WebStorm and VSCode make use of JSDoc comments for code completion. What's interesting is that you can use TypeScript definitions within @type or @param! You'll get an improved IntelliSense without migrating your project to TypeScript:

Editor autocomplete with available Jest config properties

Here are some common examples:

  • Jest configuration file:
// jest.config.js

/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = { ... }
  • ESLint configuration file:
// .eslintrc.js

/** @type {import('@types/eslint').Linter.BaseConfig} */
module.exports = { ... }
  • Tailwind configuration file:
// tailwind.config.js

/** @type {import('@types/tailwindcss/tailwind-config').TailwindConfig} */
module.exports = { ... }
  • Eleventy configuration type definition (you can also copy the type file into your project, to be used as a local import):
// .eleventy.js

/** @param { import("@darekkay/11ty/types/eleventy").Config } config */
module.exports = function (config) { ... }
  • Storybook main.js configuration file:
// .storybook/main.js 

/** @type {import("@storybook/core-common").StorybookConfig} */
module.exports = { ... }

Don't forget to add the corresponding dependencies, e.g.:

$ yarn add -D @jest/types         # Jest
$ yarn add -D @types/eslint # ESLint
$ yarn add -D @types/tailwindcss # Tailwind

This technique is also useful in projects that are in the middle of a TypeScript migration, i.e., when you mix JavaScript and TypeScript files.

Want to leave a comment?

Join the discussion at Twitter or Mastodon. Feel free to drop me an email. 💌

Import TypeScript types in JavaScript projects