Was this page helpful?

Migrating from JavaScript

TypeScript doesn’t exist in a vacuum.It was built with the JavaScript ecosystem in mind, and a lot of JavaScript exists today.Converting a JavaScript codebase over to TypeScript is, while somewhat tedious, usually not challenging.In this tutorial, we’re going to look at how you might start out.We assume you’ve read enough of the handbook to write new TypeScript code.

If you’re looking to convert a React project, we recommend looking at theReact Conversion Guide first.

Setting up your Directories

If you’re writing in plain JavaScript, it’s likely that you’re running your JavaScript directly,where your.js files are in asrc,lib, ordist directory, and then run as desired.

If that’s the case, the files that you’ve written are going to be used as inputs to TypeScript, and you’ll run the outputs it produces.During our JS to TS migration, we’ll need to separate our input files to prevent TypeScript from overwriting them.If your output files need to reside in a specific directory, then that will be your output directory.

You might also be running some intermediate steps on your JavaScript, such as bundling or using another transpiler like Babel.In this case, you might already have a folder structure like this set up.

From this point on, we’re going to assume that your directory is set up something like this:

projectRoot
├── src
│ ├── file1.js
│ └── file2.js
├── built
└── tsconfig.json

If you have atests folder outside of yoursrc directory, you might have onetsconfig.json insrc, and one intests as well.

Writing a Configuration File

TypeScript uses a file calledtsconfig.json for managing your project’s options, such as which files you want to include, and what sorts of checking you want to perform.Let’s create a bare-bones one for our project:

json
{
"compilerOptions": {
"outDir":"./built",
"allowJs":true,
"target":"es5"
},
"include": ["./src/**/*"]
}

Here we’re specifying a few things to TypeScript:

  1. Read in any files it understands in thesrc directory (withinclude).
  2. Accept JavaScript files as inputs (withallowJs).
  3. Emit all of the output files inbuilt (withoutDir).
  4. Translate newer JavaScript constructs down to an older version like ECMAScript 5 (usingtarget).

At this point, if you try runningtsc at the root of your project, you should see output files in thebuilt directory.The layout of files inbuilt should look identical to the layout ofsrc.You should now have TypeScript working with your project.

Early Benefits

Even at this point you can get some great benefits from TypeScript understanding your project.If you open up an editor likeVS Code orVisual Studio, you’ll see that you can often get some tooling support like completion.You can also catch certain bugs with options like:

TypeScript will also warn about unreachable code and labels, which you can disable withallowUnreachableCode andallowUnusedLabels respectively.

Integrating with Build Tools

You might have some more build steps in your pipeline.Perhaps you concatenate something to each of your files.Each build tool is different, but we’ll do our best to cover the gist of things.

Gulp

If you’re using Gulp in some fashion, we have a tutorial onusing Gulp with TypeScript, and integrating with common build tools like Browserify, Babelify, and Uglify.You can read more there.

Webpack

Webpack integration is pretty simple.You can usets-loader, a TypeScript loader, combined withsource-map-loader for easier debugging.Simply run

shell
npm install ts-loader source-map-loader

and merge in options from the following into yourwebpack.config.js file:

js
module.exports = {
entry:"./src/index.ts",
output: {
filename:"./dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool:"source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["",".webpack.js",".web.js",".ts",".tsx",".js"],
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{test: /\.tsx?$/,loader:"ts-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{test: /\.js$/,loader:"source-map-loader" },
],
},
// Other options...
};

It’s important to note that ts-loader will need to run before any other loader that deals with.js files.

You can see an example of using Webpack in ourtutorial on React and Webpack.

Moving to TypeScript Files

At this point, you’re probably ready to start using TypeScript files.The first step is to rename one of your.js files to.ts.If your file uses JSX, you’ll need to rename it to.tsx.

Finished with that step?Great!You’ve successfully migrated a file from JavaScript to TypeScript!

Of course, that might not feel right.If you open that file in an editor with TypeScript support (or if you runtsc --pretty), you might see red squiggles on certain lines.You should think of these the same way you’d think of red squiggles in an editor like Microsoft Word.TypeScript will still translate your code, just like Word will still let you print your documents.

If that sounds too lax for you, you can tighten that behavior up.If, for instance, youdon’t want TypeScript to compile to JavaScript in the face of errors, you can use thenoEmitOnError option.In that sense, TypeScript has a dial on its strictness, and you can turn that knob up as high as you want.

If you plan on using the stricter settings that are available, it’s best to turn them on now (seeGetting Stricter Checks below).For instance, if you never want TypeScript to silently inferany for a type without you explicitly saying so, you can usenoImplicitAny before you start modifying your files.While it might feel somewhat overwhelming, the long-term gains become apparent much more quickly.

Weeding out Errors

Like we mentioned, it’s not unexpected to get error messages after conversion.The important thing is to actually go one by one through these and decide how to deal with the errors.Often these will be legitimate bugs, but sometimes you’ll have to explain what you’re trying to do a little better to TypeScript.

Importing from Modules

You might start out getting a bunch of errors likeCannot find name 'require'., andCannot find name 'define'..In these cases, it’s likely that you’re using modules.While you can just convince TypeScript that these exist by writing out

ts
// For Node/CommonJS
declarefunctionrequire(path:string):any;

or

ts
// For RequireJS/AMD
declarefunctiondefine(...args:any[]):any;

it’s better to get rid of those calls and use TypeScript syntax for imports.

First, you’ll need to enable some module system by setting TypeScript’smodule option.Valid options arecommonjs,amd,system, andumd.

If you had the following Node/CommonJS code:

js
varfoo =require("foo");
foo.doStuff();

or the following RequireJS/AMD code:

js
define(["foo"],function (foo) {
foo.doStuff();
});

then you would write the following TypeScript code:

ts
importfoo =require("foo");
foo.doStuff();

Getting Declaration Files

If you started converting over to TypeScript imports, you’ll probably run into errors likeCannot find module 'foo'..The issue here is that you likely don’t havedeclaration files to describe your library.Luckily this is pretty easy.If TypeScript complains about a package likelodash, you can just write

shell
npm install -S @types/lodash

If you’re using a module option other thancommonjs, you’ll need to set yourmoduleResolution option tonode.

After that, you’ll be able to import lodash with no issues, and get accurate completions.

Exporting from Modules

Typically, exporting from a module involves adding properties to a value likeexports ormodule.exports.TypeScript allows you to use top-level export statements.For instance, if you exported a function like so:

js
module.exports.feedPets =function (pets) {
// ...
};

you could write that out as the following:

ts
exportfunctionfeedPets(pets) {
// ...
}

Sometimes you’ll entirely overwrite the exports object.This is a common pattern people use to make their modules immediately callable like in this snippet:

js
varexpress =require("express");
varapp =express();

You might have previously written that like so:

js
functionfoo() {
// ...
}
module.exports =foo;

In TypeScript, you can model this with theexport = construct.

ts
functionfoo() {
// ...
}
export =foo;

Too many/too few arguments

You’ll sometimes find yourself calling a function with too many/few arguments.Typically, this is a bug, but in some cases, you might have declared a function that uses thearguments object instead of writing out any parameters:

js
functionmyCoolFunction() {
if (arguments.length ==2 && !Array.isArray(arguments[1])) {
varf =arguments[0];
vararr =arguments[1];
// ...
}
// ...
}
myCoolFunction(
function (x) {
console.log(x);
},
[1,2,3,4]
);
myCoolFunction(
function (x) {
console.log(x);
},
1,
2,
3,
4
);

In this case, we need to use TypeScript to tell any of our callers about the waysmyCoolFunction can be called using function overloads.

ts
functionmyCoolFunction(f: (x:number)=>void,nums:number[]):void;
functionmyCoolFunction(f: (x:number)=>void, ...nums:number[]):void;
functionmyCoolFunction() {
if (arguments.length ==2 && !Array.isArray(arguments[1])) {
varf =arguments[0];
vararr =arguments[1];
// ...
}
// ...
}

We added two overload signatures tomyCoolFunction.The first checks states thatmyCoolFunction takes a function (which takes anumber), and then a list ofnumbers.The second one says that it will take a function as well, and then uses a rest parameter (...nums) to state that any number of arguments after that need to benumbers.

Sequentially Added Properties

Some people find it more aesthetically pleasing to create an object and add properties immediately after like so:

js
varoptions = {};
options.color ="red";
options.volume =11;

TypeScript will say that you can’t assign tocolor andvolume because it first figured out the type ofoptions as{} which doesn’t have any properties.If you instead moved the declarations into the object literal themselves, you’d get no errors:

ts
letoptions = {
color:"red",
volume:11,
};

You could also define the type ofoptions and add a type assertion on the object literal.

ts
interfaceOptions {
color:string;
volume:number;
}
letoptions = {}asOptions;
options.color ="red";
options.volume =11;

Alternatively, you can just sayoptions has the typeany which is the easiest thing to do, but which will benefit you the least.

any,Object, and{}

You might be tempted to useObject or{} to say that a value can have any property on it becauseObject is, for most purposes, the most general type.Howeverany is actually the type you want to use in those situations, since it’s the mostflexible type.

For instance, if you have something that’s typed asObject you won’t be able to call methods liketoLowerCase() on it.Being more general usually means you can do less with a type, butany is special in that it is the most general type while still allowing you to do anything with it.That means you can call it, construct it, access properties on it, etc.Keep in mind though, whenever you useany, you lose out on most of the error checking and editor support that TypeScript gives you.

If a decision ever comes down toObject and{}, you should prefer{}.While they are mostly the same, technically{} is a more general type thanObject in certain esoteric cases.

Getting Stricter Checks

TypeScript comes with certain checks to give you more safety and analysis of your program.Once you’ve converted your codebase to TypeScript, you can start enabling these checks for greater safety.

No Implicitany

There are certain cases where TypeScript can’t figure out what certain types should be.To be as lenient as possible, it will decide to use the typeany in its place.While this is great for migration, usingany means that you’re not getting any type safety, and you won’t get the same tooling support you’d get elsewhere.You can tell TypeScript to flag these locations down and give an error with thenoImplicitAny option.

Strictnull &undefined Checks

By default, TypeScript assumes thatnull andundefined are in the domain of every type.That means anything declared with the typenumber could benull orundefined.Sincenull andundefined are such a frequent source of bugs in JavaScript and TypeScript, TypeScript has thestrictNullChecks option to spare you the stress of worrying about these issues.

WhenstrictNullChecks is enabled,null andundefined get their own types callednull andundefined respectively.Whenever anything ispossiblynull, you can use a union type with the original type.So for instance, if something could be anumber ornull, you’d write the type out asnumber | null.

If you ever have a value that TypeScript thinks is possiblynull/undefined, but you know better, you can use the postfix! operator to tell it otherwise.

ts
declarevarfoo:string[] |null;
foo.length;// error - 'foo' is possibly 'null'
foo!.length;// okay - 'foo!' just has type 'string[]'

As a heads up, when usingstrictNullChecks, your dependencies may need to be updated to usestrictNullChecks as well.

No Implicitany forthis

When you use thethis keyword outside of classes, it has the typeany by default.For instance, imagine aPoint class, and imagine a function that we wish to add as a method:

ts
classPoint {
constructor(publicx,publicy) {}
getDistance(p:Point) {
letdx =p.x -this.x;
letdy =p.y -this.y;
returnMath.sqrt(dx **2 +dy **2);
}
}
// ...
// Reopen the interface.
interfacePoint {
distanceFromOrigin():number;
}
Point.prototype.distanceFromOrigin =function () {
returnthis.getDistance({x:0,y:0 });
};

This has the same problems we mentioned above - we could easily have misspelledgetDistance and not gotten an error.For this reason, TypeScript has thenoImplicitThis option.When that option is set, TypeScript will issue an error whenthis is used without an explicit (or inferred) type.The fix is to use athis-parameter to give an explicit type in the interface or in the function itself:

ts
Point.prototype.distanceFromOrigin =function (this:Point) {
returnthis.getDistance({x:0,y:0 });
};

The TypeScript docs are an open source project. Help us improve these pagesby sending a Pull Request

Contributors to this page:
DRDaniel Rosenwasser  (57)
OTOrta Therox  (14)
TAThomas Ankcorn  (3)
MGMaayan Glikser  (3)
MFMartin Fischer  (1)
19+

Last updated: May 19, 2025