Introduction
An overview of the advantages and disadvantages of TypeScript.
Advantages
1. Error detection through static code analysis
The term "static" is also understood as lexical. Lexical code analysis occurs during the creation of the AST (Abstract Syntax Tree) when analyzing a computer program. This would make sense if we were talking about processing pure JavaScript. In the case of TypeScript, we simply refer to code analysis before compilation. "Static type-checking" is like training wheels on a 5-year-old's bicycle, helping prevent falls. In our case, it prevents encountering hundreds of strange errors and behaviors from the JavaScript world. Additionally, static type-checking prevents the misuse of implementations. Consider this example:
const message = "hello";
message(); // error
// This expression is not callable.
// Type `String` has no call signatures.
The error message speaks for itself. We cannot call a primitive string
type as a function.
Moreover, if we want to achieve this, the primitive value must be passed to a Boxing mechanism.
Let's look at another example:
const a = 0;
const b = true;
const result = a + b; // error
// Operator '+' cannot be applied to
// types 'number' and 'boolean'.
In this case, the detection system doesn't allow us to add a numeric value to a boolean value. This makes sense. In the JavaScript world, the result would return the value 1.
Such a mechanism is very helpful as it allows us to eliminate all the strange mechanisms from the JavaScript world.
2. Code documentation through type annotations
Documenting the type of a parameter that is included, e.g., in a function implementation.
function toString(num: number): string {
return String(num);
}
3. Improved auto-completion
This point doesn't require much explanation. Due to the nature of TypeScript, this is quite self-explanatory.
4. Safer refactoring
In JavaScript, a method name can be implemented across different classes. This creates poor ergonomics during refactoring.
5. Downleveling
TypeScript can compile to older versions of JavaScript. In practice, it works like the Babel library. It ensures 100% backward compatibility with earlier versions of JavaScript.
tsc --target es2015 index.ts
Here's an example of how we can compile code to the ES2015 version.
Disadvantages
1. Additional layer of complexity
Unfortunately (or fortunately), you need to learn the language to use it proficiently. This adds an extra layer of complexity.
2. NPM packages must have a .d.ts file
Unfortunately, to use a given library, it must have a .d.ts file. What is this file? It's nothing more than type definitions and a way for TypeScript to understand JavaScript code.