TypeScript is a powerful, statically typed superset of JavaScript that compiles to plain JavaScript. It was developed by Microsoft to address the shortcomings of JavaScript, especially for large-scale applications. TypeScript adds optional static types, classes, and interfaces to JavaScript, making it easier to write and maintain complex codebases.

Key Concepts

  1. Static Typing: TypeScript allows you to define types for variables, function parameters, and return values, which helps catch errors at compile time rather than runtime.
  2. Type Inference: TypeScript can automatically infer types based on the values assigned to variables, reducing the need for explicit type annotations.
  3. Interfaces: Interfaces in TypeScript define the structure of an object, ensuring that objects adhere to a specific shape.
  4. Classes: TypeScript supports object-oriented programming with classes, inheritance, and access modifiers.
  5. Modules: TypeScript uses ES6 module syntax to organize code into reusable modules.
  6. Tooling: TypeScript integrates well with modern development tools, providing features like autocompletion, refactoring, and navigation.

Setting Up TypeScript

To start using TypeScript, you need to install it and set up a basic project. Follow these steps:

  1. Install TypeScript:

    npm install -g typescript
    
  2. Initialize a TypeScript Project:

    mkdir my-typescript-project
    cd my-typescript-project
    tsc --init
    
  3. Create a TypeScript File:

    touch index.ts
    
  4. Compile TypeScript to JavaScript:

    tsc
    

Basic TypeScript Syntax

Variables and Data Types

TypeScript supports various data types, including number, string, boolean, array, tuple, enum, any, void, null, and undefined.

let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let x: [string, number] = ["hello", 10]; // Tuple

Functions

Functions in TypeScript can have typed parameters and return types.

function add(x: number, y: number): number {
  return x + y;
}

let result: number = add(2, 3);

Interfaces

Interfaces define the structure of an object.

interface Person {
  firstName: string;
  lastName: string;
}

function greet(person: Person) {
  return "Hello, " + person.firstName + " " + person.lastName;
}

let user = { firstName: "John", lastName: "Doe" };
console.log(greet(user));

Classes

Classes in TypeScript support inheritance, access modifiers, and more.

class Animal {
  private name: string;

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

  public move(distance: number): void {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}

let dog = new Animal("Dog");
dog.move(10);

Practical Exercise

Exercise 1: Basic Types and Functions

  1. Create a TypeScript file named exercise1.ts.
  2. Define variables with different data types.
  3. Write a function that takes two numbers as parameters and returns their sum.
  4. Create an interface for a Car object with properties make, model, and year.
  5. Write a function that takes a Car object and returns a string describing the car.

Solution

// exercise1.ts

// Variables with different data types
let isAvailable: boolean = true;
let price: number = 19.99;
let productName: string = "Widget";
let tags: string[] = ["sale", "new", "popular"];

// Function to add two numbers
function addNumbers(a: number, b: number): number {
  return a + b;
}

let sum: number = addNumbers(5, 10);
console.log(`Sum: ${sum}`);

// Interface for a Car object
interface Car {
  make: string;
  model: string;
  year: number;
}

// Function to describe a car
function describeCar(car: Car): string {
  return `This car is a ${car.year} ${car.make} ${car.model}.`;
}

let myCar: Car = { make: "Toyota", model: "Corolla", year: 2020 };
console.log(describeCar(myCar));

Summary

In this section, we introduced TypeScript, a statically typed superset of JavaScript. We covered key concepts such as static typing, type inference, interfaces, classes, and modules. We also walked through setting up a TypeScript project and explored basic TypeScript syntax with practical examples. Finally, we provided an exercise to reinforce the learned concepts. In the next section, we will delve deeper into TypeScript variables and data types.

© Copyright 2024. All rights reserved