caracteristicas-typescript

Features of TypeScript

  • 3 min

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

Static Typing

Undoubtedly one of the distinctive 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 detect errors before running the code, improving its quality and safety.

For example, suppose we have this function,

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

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
Copied!

Whereas in JavaScript, you wouldn’t have had any warning or error that something wasn’t going well. (Which, surely, would have given you a problem at some point 😉)

Furthermore, thanks to the type system, TypeScript offers smarter autocompletion and better development assistance compared to JavaScript.

Object-Oriented Programming

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

These features help us 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.
Copied!

Compatibility with JavaScript

As I said, TypeScript is a superset of JavaScript. That is, it’s a layer on top of JavaScript.

Therefore, all 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}`;
}
Copied!

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.