Retour aux articles
Friday, December 13, 202441 vues1

Getting Started with TypeScript: The Basics Explained

Mike Codeur

Cheat Sheet
Astuces

TypeScript is an extension of JavaScript that adds static typing to your code. This helps catch errors at compile time, making your code more robust and maintainable. In this article, we will explore the basics of TypeScript with clear and concise examples to help you get started.

Why Use TypeScript?

Before diving into the code, here are some key advantages of TypeScript:

  1. Static Typing: It helps catch errors before execution.
  2. Autocomplete and Documentation: Tools like VS Code provide enhanced autocomplete and documentation thanks to TypeScript.
  3. Interoperability: TypeScript works seamlessly with existing JavaScript projects.
  4. Maintainable Code: Types facilitate team collaboration and the management of complex projects.

Installing TypeScript

To start with TypeScript, install it globally via npm:

BASH
npm install -g typescript

To verify that TypeScript is installed:

BASH
tsc --version

Your First TypeScript File

Create a file named app.ts:

TSX
function greet(name: string): string {
    return `Hello, ${name}!`;
}

const message = greet("Alice");
console.log(message);

Compile this file with the following command:

TSX
tsc app.ts

This will generate a app.js file that you can execute with Node.js.

Basic Types

1. string Type

TSX
const firstName: string = "John";

2. number Type

TSX
const age: number = 25;

3. boolean Type

TSX
const isDeveloper: boolean = true;

4. Arrays

TSX
const skills: string[] = ["TypeScript", "JavaScript", "React"];

5. Objects

TSX
const user: { name: string; age: number } = {
    name: "Alice",
    age: 30,
};

6. any Type

The any type disables type checking. However, its use should be avoided whenever possible.

TSX
let randomValue: any = "Hello";
randomValue = 42; // No issues here.

Functions in TypeScript

TypeScript allows you to define types for function parameters and return values.

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

const sum = add(10, 20);
console.log(sum);

Parameters can also be optional:

TSX
function greetUser(name: string, age?: number): string {
    return age ? `Hello, ${name}. You are ${age} years old.` : `Hello, ${name}.`;
}

console.log(greetUser("Alice"));
console.log(greetUser("Bob", 25));

Interfaces and Types

Interfaces define structures for objects.

TSX
interface User {
    name: string;
    age: number;
    isAdmin: boolean;
}

const newUser: User = {
    name: "Charlie",
    age: 28,
    isAdmin: false,
};

Types can also be used to create aliases:

TSX
type Point = {
    x: number;
    y: number;
};

const origin: Point = { x: 0, y: 0 };

Enums

enums are used to define a set of constant values.

TSX
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

const move = Direction.Up;
console.log(move); // Outputs 0 (index of the value)

Classes

TypeScript supports object-oriented programming with classes and interfaces.

TSX
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    greet(): string {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}

const person = new Person("Alice", 30);
console.log(person.greet());

Configuring tsconfig.json

To configure your TypeScript project, initialize a tsconfig.json file:

BASH
tsc --init

A typical configuration file may look like this:

TSX
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

Conclusion

TypeScript is a powerful tool for writing safer and more maintainable JavaScript code. By understanding the basics such as types, interfaces, and classes, you will be well-equipped to build robust applications.

Feel free to explore further and apply TypeScript to your existing projects to fully experience its benefits.

Abonnes-toi à la NewsLetter

Apprends les meilleures pratiques pour devenir un développeur web moderne (JavaScript / React / Next).

Gagner sa vie grâce au code
Devenir développeur Freelance
+35 000 développeurs déjà inscrits.

Accès instantané. Aucune carte de crédit requise.

Rejoins +35 000 développeurs déjà inscrits.