TypeScript or JavaScript? Developers contemplate this choice for greenfield web or Node.js projects, but it’s a question worth considering for existing projects too. A superset of JavaScript, TypeScript offers all of the features of JavaScript plus some additional perks. TypeScript intrinsically encourages us to code cleanly, making the code more scalable. However, projects can contain as much plain JavaScript as we like, so using TypeScript is not an all-or-nothing proposition.
The Relationship Between TypeScript and JavaScript
TypeScript adds an explicit type system to JavaScript, allowing for the strict enforcement of variable types. TypeScript runs its type checks while transpiling—a form of compiling that converts TypeScript code to the JavaScript code web browsers and Node.js understand.
TypeScript vs. JavaScript Examples
Let’s start with a valid JavaScript snippet:
let var1 = "Hello";
var1 = 10;
console.log(var1);
Here, var1
starts out as a string
, then becomes a number
.
Since JavaScript is only loosely typed, we can redefine var1
as a variable of any type—from a string to a function—at any time.
Executing this code outputs 10
.
Now, let’s change this code into TypeScript:
let var1: string = "Hello";
var1 = 10;
console.log(var1);
In this case, we declare var1
to be a string
. We then try to assign a number to it, which isn’t allowed by TypeScript’s strict type system. Transpiling results in an error:
TSError: ⨯ Unable to compile TypeScript:
src/snippet1.ts:2:1 - error TS2322: Type 'number' is not assignable to type 'string'.
2 var1 = 10;
If we were to instruct the transpiler to treat the original JavaScript snippet as if it were TypeScript, the transpiler would automatically infer that var1
should be a string | number
. This is a TypeScript union type, which allows us to assign var1
a string
or a number
at any time. Having resolved the type conflict, our TypeScript code would transpile successfully. Executing it would produce the same result as the JavaScript example.
TypeScript vs. JavaScript From 30,000 Feet: Scalability Challenges
JavaScript is ubiquitous, powering projects of all sizes, applied in ways that would have been unimaginable during its infancy in the 1990s. While JavaScript has matured, it falls short when it comes to scalability support. Accordingly, developers grapple with JavaScript applications that have grown in both magnitude and complexity.
Thankfully, TypeScript addresses many of the issues of scaling JavaScript projects. We’ll focus on the top three challenges: validation, refactoring, and documentation.