Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Migrate/convert JavaScript to TypeScript cheatsheet

Relevant official docs

Migrating NodeJS CJS files (require, module.exports)

First steps

  1. Rename the file from .js to .ts
  2. Change module.exports = to export =
  3. Change all exports.foobar = to export const foobar =
  4. Update top-level require calls to static import.
    • Note: You can use vscode to help you with that
    • Put the caret inside require, press cmd-. -> "Convert require to import"
    • If you have multiple require: select all those lines, and choose "Convert all require to import"
  5. Fix remaining TS errors (see below)
  6. Update inline require('foobar') to await import('foobar') or (await import('foobar')).default

Inferring function param types

  • Put the caret inside param list of a function
  • Press cmd-. -> "Infer parameter types from usage"

Adding missing .d.ts for npm modules

If you have import foobar from 'foobar' npm package imports, with TS error TS7016 like Could not find a declaration file for module 'foobar', you can try to install the type definitions as follows:

yarn add @types/foobar

After installation, you may need to do cmd-shift-p: TypeScript: Restart TS server.

Generating .d.ts from .js local files

If you have the same errors as above (TS7016) for local files, you can try to generate .d.ts file from the input .js file

yarn tsc --allowJs --declaration --emitDeclarationOnly path/to/file.js
Copy link

jakub-g commented Oct 8, 2021

Edge cases

"Convert require to import" won't work for cases like this:
const glob = require('util').promisify(require('glob'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment