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

// Tailwind < 3.1

/** @type { import("@types/tailwindcss/tailwind-config").TailwindConfig } */
module.exports = { ... }

// Tailwind 3.1+

/** @type { import("tailwindcss").Config } */
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) { ... }
  • Next.js configuration file:
// next.config.js

/** @type { import("next").NextConfig } */
module.exports = { ... }
  • 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 < 3.1

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.

Import TypeScript types in JavaScript projects