AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

TypeScript Tutorial: Static Typing in JavaScript

PARTAGEZ

TypeScript offers a number of essential features that radically improve the web application developmentThis TypeScript tutorial will help you get familiar with this programming language by explaining its main features, uses, and advantages and disadvantages.

What is TypeScript?

Developed by Microsoft, TypeScript is an extension of JavaScript that is widely used in the world of web development. One of the most notable features of TypeScript is the static typing. Unlike JavaScript, which features dynamic typing, TypeScript lets you declare data types for variables, functions, and parameters. This helps detect errors early, even before the code is executed. Static typing thus significantly improves the quality of your code while making it more readable.

TypeScript's syntax is largely identical to JavaScript's, making it easy to integrate into existing JavaScript projects. In fact, TypeScript is a superset of JavaScriptwhich means that any good JavaScript code also works with TypeScript. This allows you to gradually move to TypeScript and enjoy the benefits of static typing and other features without having to completely rewrite your existing codebase.

Here is a simple JavaScript example:

function greet(name) {
    return "Hello, " + name;
}
console.log(greet(123)); // Output: "Hello, 123"

javascript

In this JavaScript code, the function greet is not limited to a particular data type for the parameter name. Thus, the function can be called without error, even when a number is passed as an argument.

In TypeScript, the code looks like this:

function greet(name: string): string {
    return "Hello, " + name;
}
console.log(greet(123)); // Error in TypeScript

typescript

Here we have explicitly declared the parameter name as a string (string). If we now try to call the function with a number, TypeScript will display an error because the data type passed as a parameter does not match the expected data type.

This example highlights TypeScript's ability to help you spot errors early and improve the quality of your code by avoiding using incorrect data types. However, it is important to remember that TypeScript is converted to JavaScript. This allows it to work in any JavaScript environment, but also means that the benefits of type safety are only available during the development phase.

TypeScript Application Areas

TypeScript is an essential element in different application areas of software development, especially in situations where the type safety and code quality are of paramount importance.

Web development is an important application area for TypeScript. In this area, TypeScript allows you to write safer and more maintainable JavaScript code. This is an advantage for large frontend projects where the code base is complex. But TypeScript can also be implemented on the frontend side. server (backend) in Node.js applications to provide an additional layer of security. In serverless architectures like AWS Lambda and Azure Functions, TypeScript helps minimize errors and ensure reliable execution.

Cross-platform development is another area where TypeScript shows its strengths. It can significantly optimize the cross-platform application and mobile application development. Frameworks like NativeScript and React Native provide support for TypeScript in mobile app programming for different platforms. In game development, TypeScript is used in projects that use WebGL or game engines like Phaser or Babylon.js. TypeScript's type safety helps improve the quality and maintainability of games.

For projects of data visualization and analysisTypeScript is also used. Libraries like D3.js provide support for TypeScript and allow you to create sophisticated dashboards and visualizations.

Installing TypeScript is simple and only requires a few steps. You can install TypeScript with npm (Node Package Manager) if you have Node.js on your computer.

Step 1: Download Node.js

Make sure you have Node.js installed on your computer. If you haven't set up Node.js yet, you can download it from the official website and install it.

Step 2: Install TypeScript on your terminal

Open your command line (e.g. Windows Command Prompt, Terminal on macOS, or Linux) and enter the following command to install TypeScript on your system:

npm install -g typescript

bash

With the flag -g (overall), TypeScript is installed on your entire system, allowing you to use it from anywhere.

Step 3: View the installed version

You can test if the installation was successful by running the following command:

This command displays the installed version of TypeScript. If you see the version numberthe installation was successful.

After installation, you can create TypeScript files (with .ts extension) and compile them with the TypeScript compiler tsc For generate JavaScript files.

Step 4: Create a TypeScript file

Create a TypeScript file, for example app.tsand insert your TypeScript code.

type Person = { name: string, age: number };
const alice: Person = { name: "Alice", age: 30 };
console.log(`Hello, I am ${alice.name} and I am ${alice.age} years old.`);

typescript

Step 5: Compile the file

Compile the TypeScript file by typing the following command:

This will compile app.ts into a JavaScript file named app.js. You can then run the JavaScript file.

TypeScript Features

Web development has come a long way in recent years, and TypeScript has emerged as an alternative extremely powerful JavaScript. We have summarized the main features of TypeScript for you below.

Static typing

Static typing is a core aspect of TypeScript and is concerned with defining data types for variables, parameters, functions, and other elements of your code. Unlike dynamic typing in JavaScriptin which data types are determined at runtime, the declaration of data types in TypeScript takes place during development, i.e. before the code is executed. Types therefore help to detect errors and logical problems at an early stage.

function add(a: number, b: number): number {
    return a + b;
}
const result = add(5, 3); // valid
const result = add(5, "3"); // Type Error

typescript

In this example we use static typing for the function add. The two parameters a And b are declared as numbers (number) and the function returns a value of type number. So attempts to call this function with other data types are recognized as errors by TypeScript.

Optional typing

Optional typing allows you to assign types to some variables and parameters, while leaving others without explicit typing.

function sayHello(name: string, age: any): string {
    if (age) {
        return `Hello, ${name}, you are ${age} years old.`;
    } else {
        return `Hello, ${name}.`;
    }
}

typescript

Function sayHello is defined with the parameters name And age. The term any indicates that the parameter age can take any data type.

ES6+ Functions

TypeScript supports modern JavaScript features, including ES6 and newer features like arrow functions (Arrow Functions) and template strings.

const multiply = (a: number, b: number): number => a * b;
const greeting = (name: string) => `Hello, ${name}!`;

typescript

Arrow functions lead to shorter, more concise syntax.

Code organization

With modules and namespaces, TypeScript provides better code organization and ensures the division of code into reusable parts.

// Math.ts
export function add(a: number, b: number): number {
    return a + b;
}
// Main.ts
import { add } from './Math';
const result = add(5, 3);

typescript

Here we illustrate the organization of code using modules and the use of import And export. Function add is defined in a separate module Math.ts and imported and integrated into another module Main.ts.

Object-oriented programming (OOP)

TypeScript makes object-oriented programming easier because it includes the use of TypeScript classes, interfaces, and inheritance.

class Person {
    constructor(public name: string, public age: number) {}
    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}
const person = new Person("Alice", 30);
person.greet();

typescript

This example demonstrates the use of classes and object-oriented programming (OOP) in TypeScript. The class Person has the properties name, age and a method greet to introduce yourself and give information about yourself.

Extended Type System

TypeScript's type system is flexible and extensive. You can create user-defined types and interfaces and even extend existing types.

interface Animal {
    name: string;
}
interface Dog extends Animal {
    breed: string;
}
const myDog: Dog = { name: "Buddy", breed: "Labrador" };

typescript

The interface Animal defines a property namewhile the interface Dog inherits from Animal and adds an additional property breed. The object myDog has the characteristics of both interfaces.

JavaScript Compatibility

TypeScript is compatible with JavaScript and can be run in any JavaScript environment. This makes it easy to gradually introduce TypeScript into existing JavaScript projects.

// JavaScript-Code
function greet(name) {
    return "Hello, " + name;
}
// TypeScript-Code
function greet(name: string): string {
    return "Hello, " + name;
}

typescript

JavaScript code (without type) can be used without any problem in TypeScript code (with type).

What are the advantages and disadvantages of TypeScript?

TypeScript offers a multitude of benefits, but also has some drawbacks. Here's a look at the pros and cons:

Benefits

TypeScript has a large ecosystem of type definitions for many JavaScript libraries and frameworks. This makes integrating third-party code into TypeScript projects seamless and easy. This is useful in today's web-based applications, which often depend on multiple libraries and frameworks.

In addition to static typing, TypeScript offers a host of development features, including interfaces, classes, modules, and the support for current ECMAScript standards. These features improve code structuring, facilitate project maintainability and scalability, and promote development productivity. TypeScript is also very well supported by many integrated development environments (IDEs) such as Visual Studio Code.

Disadvantages

TypeScript requires a certain period of learningespecially if developers have previously only worked with JavaScript. Additionally, TypeScript code must be compiled to JavaScript before it can be run in browsers or Node.js environments, which adds an extra step to the development process.

For small projects, TypeScript may be perceived as too complex, because the benefits of type safety may not be as obvious. TypeScript projects may require more resources due to the additional type information required, and the additional step of compilation.

Alternatives to TypeScript

There are several alternative web programming languages ​​to TypeScript, depending on a project's specific needs and developer preferences.

  • Flow : Flow is a static typing for JavaScript developed by Facebook. It allows you to add types to JavaScript code without having to do a full conversion to TypeScript. Flow is a good choice if you want to gradually integrate typing into your JavaScript projects.

  • Dart : It is a programming language developed by Google that can be used to create web and mobile applications. It offers type safety and good performance. Dart is often used in combination with the Flutter framework for mobile application development.

  • PureScript : PureScript serves as a strictly typed functional programming language, which includes strong type safety and functional programming style. It allows importing JavaScript libraries.

  • Elm : Elm is a strictly typed, functional language designed for developing web applications. Elm promotes the principle of « Elm architecture » and has strong type safety.

  • ReasonML (BuckleScript) : This language is developed by Facebook and is based on OCaml. BuckleScript is a compiler that compiles ReasonML to JavaScript. It also provides type safety and strong integration with React for frontend development.

Advice

Check out our other articles on the topics of TypeScript functions and TypeScript arrays.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact