0% completed
Comparing JavaScript vs TypeScript
On This Page
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.
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
| Feature | JavaScript | TypeScript |
|---|---|---|
| Typing | Dynamic: types are examined at runtime | Static: types are checked at compile time, then removed |
| Error detection | Type mistakes appear when the line runs | Type mistakes appear during development; bad data from outside still appears at runtime |
| Running the code | Runs directly | Usually compiled to JavaScript first |
| Runtime speed | Same | Same, because the same JavaScript runs |
| Editor support | Autocomplete based on what the editor can work out | Autocomplete and real-time errors based on declared types |
| Code maintainability | Less structured | More structured, with types that document the code |
| Scalability | Can be difficult for large projects | Designed for large-scale applications |
| Object-oriented support | Classes and inheritance (ES6 and later) | Adds interfaces and access modifiers |
| Generics | Not needed, because there are no static types | Reusable typed code, which a later chapter covers |
| Learning curve | Easier for beginners | Requires 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%
On This Page
TypeScript Runs as JavaScript
Side by Side