Skip to content

Instantly share code, notes, and snippets.

@jakub-g
Last active February 14, 2024 00:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakub-g/e6e52a28b59b3140d5f53e378937426c to your computer and use it in GitHub Desktop.
Save jakub-g/e6e52a28b59b3140d5f53e378937426c to your computer and use it in GitHub Desktop.
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
@jakub-g
Copy link
Author

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