Grokking TypeScript
Vote

0% completed

​

Comparing JavaScript vs TypeScript

TypeScript Runs as JavaScript

Side by Side

The same one-line mistake behaves very differently in the two languages:

console.log(calculateTotal("20", 5));

In JavaScript, this line runs and prints 205, and you learn about the bug when someone reports a wrong total. In TypeScript, with price annotated as number, the compiler reports error TS2345 before you run the program. Most differences between the two languages follow from when that mistake becomes visible.

The same mistake found by a user at runtime in JavaScript and by the compiler before the run in TypeScript.
The same mistake found by a user at runtime in JavaScript and by the compiler before the run in TypeScript.

TypeScript Runs as JavaScript

Browsers run JavaScript, not TypeScript. The normal path is therefore to compile the TypeScript file, which removes the types and produces a JavaScript file, and then to run that file. At runtime, there is only JavaScript, so the program runs at the same speed and behaves the same way.

Recent versions of Node.js can run a .ts file directly, because they remove the types when they load the file. They do not check the types, however, as this small test shows:

const quantity: number = "not a number"; console.log(quantity);
node check.ts
not a number

The type error did not stop the program, because only the compiler, tsc, performs the check. In a project, you still run tsc or use an editor that reports the same errors.

Side by Side

FeatureJavaScriptTypeScript
TypingDynamic: types are examined at runtimeStatic: types are checked at compile time, then removed
Error detectionType mistakes appear when the line runsType mistakes appear during development; bad data from outside still appears at runtime
Running the codeRuns directlyUsually compiled to JavaScript first
Runtime speedSameSame, because the same JavaScript runs
Editor supportAutocomplete based on what the editor can work outAutocomplete and real-time errors based on declared types
Code maintainabilityLess structuredMore structured, with types that document the code
ScalabilityCan be difficult for large projectsDesigned for large-scale applications
Object-oriented supportClasses and inheritance (ES6 and later)Adds interfaces and access modifiers
GenericsNot needed, because there are no static typesReusable typed code, which a later chapter covers
Learning curveEasier for beginnersRequires learning type annotations and the type system

JavaScript without a build step remains a reasonable choice for a short script that one person maintains. TypeScript justifies its extra cost when a codebase has many files or several developers, because the compiler then checks connections between code that no single person remembers.

Reading Progress

0%


Vote for new content

On This Page

TypeScript Runs as JavaScript

Side by Side