Language: EN

caracteristicas-typescript

Features of TypeScript

We started the course by looking at some of the most important characteristic advantages of TypeScript, which have made it a popular and rapidly growing language.

Static Typing

Undoubtedly, one of the distinguishing features of TypeScript is static typing. Unlike JavaScript, where types are determined at runtime, TypeScript allows us to define the types of variables, parameters, and function returns at development time.

This helps to catch errors before executing the code, improving its quality and safety.

For example, let’s assume we have this function,

function sum(a: number, b: number): number {
    return a + b;
}

Here we have defined that sum is a function that accepts two parameters of type number and returns a number.

If we try to pass a string as an argument, TypeScript will throw an error at compile time.

sum("1", "2");  // this will give you an error before compiling

Whereas in JavaScript, you would not have had any warning or error that something was going wrong. (Which, surely, would have caused you some problems at some point 😉)

Additionally, thanks to the type system, TypeScript offers smarter autocompletion and better help in development compared to JavaScript.

Object-Oriented Programming

TypeScript introduces object-oriented programming (OOP) concepts such as classes, interfaces, and inheritance, which are not native to JavaScript (although some are present).

These features help us to organize and structure the code, especially in large projects.

class Animal {
    constructor(public name: string) {}
    
    makeSound(): void {
        console.log(`${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    bark(): void {
        console.log(`${this.name} barks.`);
    }
}

const myDog = new Dog('Firulais');
myDog.makeSound(); // Firulais makes a sound.
myDog.bark(); // Firulais barks.

Compatibility with JavaScript

As I mentioned, TypeScript is a superset of JavaScript. That is, it is a layer placed on top of JavaScript.

Therefore, any valid JavaScript code is also valid TypeScript code. This allows us to gradually migrate an existing JavaScript project to TypeScript (without having to rewrite all the code from scratch).

// Valid JavaScript code
function greet(name) {
    return `Hello, ${name}`;
}

// We can gradually convert it to TypeScript
function greet(name: string): string {
    return `Hello, ${name}`;
}

Integration with Tools and Frameworks

TypeScript integrates perfectly with numerous popular frameworks and libraries, such as Angular, React, and Vue.js. In fact, Angular is written in TypeScript, which has contributed to its adoption.

Integration with modern development tools, such as code editors and build systems, is also excellent. For example, Visual Studio Code, developed by Microsoft, offers native support for TypeScript, including autocompletion and refactoring.