TypeScript-JavaScript Interop

Published on: 06, by YS

The ideal strategy is to migrate the project from plain ECMAScript (JavaScript, ES hereafter) to TypeScript altogether. For a large code base, a big-bang migration is not feasible nor desirable, but you can always start in small pieces and iterate.

One way is for new applications to start with TS and re(use) JS libraries when needed. Refer to the section below on ​"TS code using JS library"

For existing codebase, it is possible to iteratively migrate custom library packages to TS first. The TS libraries would be built into ES5 by specifying the target and published to the package registry. Then the legacy application would use the library as any other JS library, as it was transpiled into JS. See section below on "​JS code using TS library"

​TS code using ES library

If Type Definition Is Provided in Another Package, Use It

If you are using 3rd party libraries (e.g. open source), there is a high chance that it already provides type definitions (*.d.ts). The new usually already includes the type definition within the package, old/existing libraries may need to install additional libraries with the @types scope.

For example the type definition package for koa is @types/koa.

If There Is No Type Definition, Create One

If you are using a library that does not have type definition (yet), i.e. your own code, you can create the type definition.

When you try to compile, you will get error on the line that is importing the JS module:

Cannot find module 'your-module-name' or its corresponding type declarations.

At minimum, you can create a file called declarations.d.ts in the source directory and add all the modules which does not have definitions, e.g.

declare module 'your-module-name' {
// Declare the structures that are exported in the original JS code.
}
...

An example is:

declare module "workflow-commons" {

export class WorkflowError {
constructor(message?: string);
}

}

Once the declaration is added, the IDE will correctly apply to the occurrence of WorkflowError and if the parameter type is incorrect will show with red underline.

ES Code Using TS Library

As long as the TS is transpiled into ES the library should be ready to be used by ES. If you are converting an ES module int TS module, see ​ “Publishing Custom TS Module with Type Definitions: section above.

Depending on the IDE, you may still get parameter type hints.

​References

  1. Migrating from JavaScript, TypeScript
  2. Adding Custom Type Definitions to a Third-Party Library,detroitlabs.com

Published on: 06, by YS

Edit on Git