TypeScript: Why It's Needed and Why It's So Popular
JavaScript code should work predictably in any situation. We could add many checks to our code, but that would make it bulky and hard to maintain. We could also add comments and hints, but they won’t protect us from incorrect code usage. In this situation, TypeScript comes to the rescue. Let’s explore why it's so useful for JavaScript developers.
What is TypeScript?
TypeScript is a strongly typed programming language based on JavaScript. It consists of three main parts:
- Language syntax,
- Compiler,
- Editor service.
TypeScript syntax allows developers to express solutions elegantly in .ts or .tsx files. It’s an evolution of JavaScript’s syntax, meaning any JS program is syntactically valid in TypeScript.
The tsc compiler helps catch many defects before deployment. It transforms TypeScript source code into JavaScript and analyzes the program to identify potential issues. TypeScript can generate .js files for any version of JavaScript, starting from ES3. Developers can configure TypeScript to enable or disable specific analysis rules.
These defects aren’t always errors. Sometimes they don’t break the requirements for a long time, but when new client demands appear, these issues can cause unnecessary project costs.
For instance, in JavaScript, there’s a try...catch operator. The catch block receives an error value, which can be anything—like a string, a number, or an object. In JavaScript, developers rely on "experience and intuition," often assuming that the error will be of type Error.
In TypeScript, you can have the compiler check the usage of the catch value, or you can turn off this rule:
catch(err){
console.log(err.message)
}
An error will be raised if err is, say, the number 42.
If you set the compiler flag useUnknownInCatchVariables, the compiler will disallow the code above. It will force the developer to think of a solution, reducing the risk of program crashes.
The editor service performs the same analysis as the tsc compiler but does so as you write the program. Many editors support TypeScript—for example, VS Code, Atom, WebStorm, and Sublime Text. If your preferred editor isn’t on this list, you can use the TS Playground sandbox to get familiar with TypeScript.
The TS Playground online editor is designed for learning TypeScript. It lets you explore all key aspects of this language, connect modules from npm, study compiler flags, and review generated JavaScript and module definition files (.d.ts). However, its capabilities for running JavaScript are limited.
TypeScript compiler services guide you by pointing out errors as you write your code.
What Does the Community Say?
| Language Popularity on SO | 2020 | 2021 |
|---|---|---|
| JavaScript | 67% | 65% |
| TypeScript | 25% | 30% |
| Language Share of Pull Requests | Change from Last Year |
|---|---|
| JavaScript | 14.1% |
| TypeScript | 8.5% |
Developers often note that junior and mid-level new hires onboard faster in a TypeScript-based project than in a JavaScript one. It's no surprise that knowledge of TypeScript is becoming a plus for job candidates.
Studies on programming language usage based on GitHub user stats show that TypeScript is one of the most common languages developers switch to. It seems developers are increasingly abandoning languages like CoffeeScript to start coding in TypeScript.
TypeScript's Role in Your Work
TypeScript’s creators aim to help developers create and grow products for any system that can run JavaScript, giving developers confidence that their code will execute predictably.
Programs are like theorems: they consist of statements, and we can question whether these statements contain contradictions. This is important because, in the presence of contradictions, a program may fail at runtime.
Ensuring the absence of contradictions in TypeScript is easier than in JavaScript. It’s all about type annotations.
In TypeScript, every variable, function, and class explicitly or implicitly carries hints about the type of values it holds. These hints are accessible not only to developers but also to the editor and compiler. Thanks to these annotations, TypeScript services help catch logical contradictions in the source code.
Here’s how TypeScript services can "reason" through code like this:
const title = "TypeScript"; console.log(title.toUpperCase());
- It's known that the
toUpperCasemethod can be applied to a string. console.logis available in any JavaScript runtime.- The developer declared an immutable variable.
- The value of the declared variable is a string.
- Since (1), (3), and (4) are true, the
toUpperCasemethod can always be applied to the variable.
Thus, because of (2) and (5), the program will always run successfully.
This reasoning chain is enabled by TypeScript’s knowledge of what can and cannot be done with variable values.
Often, TypeScript can infer actions on its own. For example, it’s well-versed in primitive values inherited from JavaScript. For custom types, developers can clarify their intentions to TypeScript.
This is the essence of working with TypeScript: you tell it what values you intend to use, and it suggests which operations can be applied in various situations. Here’s another example of TypeScript’s "reasoning":
let title: string; console.log(title.toUpperCase());
The developer intends to use string values in the variable, but the variable is uninitialized. Without a value, toUpperCase can’t be applied.
After this reasoning, TypeScript reports the error: Variable 'title' is used before being assigned, even before the program runs. And before you finish typing the second semicolon! By then, you haven't forgotten why you declared the title variable, saving you time fixing the issue.
Often, TypeScript's ability to catch these types of defects and require developers to address them is frustrating for beginners. After all, who enjoys admitting mistakes? But with experience comes the understanding that compiler hints are essential for creating quality products.
TypeScript is much more than a type-checking service. It also:
- Defines syntax so developers can express the intent to use specific types (
let title: string;). - Controls the validity of using values within the program context (
title.toUpperCase()). - Notifies developers of incorrect operations with variables right in the editor, before running the program.
- Enables development in an OOP style, supporting keywords like
private,protected,public,abstract,extends, andimplements. - Compiles to any JavaScript version from ES3 and up.
- Allows using modules in any format.
- Enables generic programming, allowing developers to create components that implement algorithms in a general way.
- Supports aspect-oriented programming through the non-standard decorator feature.
- Allows adding type annotations to existing JavaScript libraries, including standard ones.
- Compiles JSX not just for React; you can provide your own
createElementimplementation. - Integrates with Babel, Browserify, Grunt, Gulp, Jspm, MSBuild, NuGet, Rollup, Svelte Compiler, Vite, Webpack.
- Is an open-source project under Microsoft.
And this is only a fraction of the valuable features and capabilities that TypeScript offers.
TypeScript’s Assistance in Action
During compilation, TypeScript generates clean JavaScript. You can see this in the TypeScript Playground. Here’s what happens to a class definition in older JavaScript versions:
TypeScript
class Example{}
Compiler flag target=ES3
"use strict";
var Example = /** @class */ (function () {
function Example() {
}
return Example;
}());
Clearly, it’s easier to write a single line in TypeScript and run the compiler rather than manually write an IIFE.
Creating infrastructure code manually is risky due to the potential for errors that are hard to spot. TypeScript formats modules of any standard for you. Here’s how it formats a UMD module:
TypeScript
export const Component = (props: ComponentProps) => {
const { delay } = props;
const [elapsed, setElapsed] = useState(false);
useEffect(() => {
let cleaned = false;
setTimeout(() => {
if (cleaned) {
return;
}
setElapsed(true);
}, delay);
return () => { cleaned = true; };
}, [delay])
return <h1>{elapsed ? 'loading' : 'completed'}</h1>
}
Compiled JavaScript (module=UMD)
function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "react"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Component = void 0;
const react_1 = require("react");
const Component = (props) => {
const { delay } = props;
const [elapsed, setElapsed] = (0, react_1.useState)(false);
(0, react_1.useEffect)(() => {
let cleaned = false;
setTimeout(() => {
if (cleaned) {
return;
}
setElapsed(true);
}, delay);
return () => { cleaned = true; };
}, [delay]);
return React.createElement("h1", null, elapsed ? 'loading' : 'completed');
};
exports.Component = Component;
});
Where Will You Encounter TypeScript?
When working with Angular, developers are often required to use TypeScript. Other popular frameworks and libraries support TypeScript, as it compiles plain JavaScript. Many projects, like Redux, are now written in TypeScript and distributed as compiled npm packages.
TypeScript also enables developers to methodically and predictably port codebases from JavaScript. This capability makes TypeScript invaluable for maintaining legacy projects.
What’s Next?
TypeScript is closely related to JavaScript but has its own syntax and compilation system. Leveraging these features can significantly reduce programming errors, yielding more predictable results during development and refactoring. However, TypeScript requires knowledge and skill.
To use TypeScript effectively, developers need to create and describe types and understand how they interact. In our view, it’s better to invest time in learning TypeScript now than to avoid it and face greater challenges later.
Should you use TypeScript in every project, or is it inherently better than other languages? These questions don’t have straightforward answers. The right question is what benefits TypeScript brings to your project. As the project grows and new requirements emerge, TypeScript will increasingly prove to be more advantageous than JavaScript.
Comments
Post a Comment