DEV Community

Cover image for Introduction to TypeScript
_Khojiakbar_
_Khojiakbar_

Posted on • Updated on

Introduction to TypeScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static types to your code, making it easier to catch errors during development.

Setting Up TypeScript
First, let's set up TypeScript:

  1. Install TypeScript globally using npm:
npm install -g typescript
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a TypeScript project:
tsc --init
Enter fullscreen mode Exit fullscreen mode
  1. Compile TypeScript:

To compile a TypeScript file (.ts), run:

tsc filename.ts
Enter fullscreen mode Exit fullscreen mode

Basic Types

Let's start with some basic types and funny examples.

1. Primitive Types

  • String
let greeting: string = "Hello, TypeScript!";
console.log(greeting); // Hello, TypeScript!
Enter fullscreen mode Exit fullscreen mode
  • Number
let age: number = 42;
console.log(`I'm ${age} years old!`); // I'm 42 years old!
Enter fullscreen mode Exit fullscreen mode
  • Boolean
let isHappy: boolean = true;
console.log(`Am I happy? ${isHappy}`); // Am I happy? true
Enter fullscreen mode Exit fullscreen mode

Imagine a robot that can only understand specific types:

let robotName: string = "RoboCop";
let robotAge: number = 100;
let isRobotFriendly: boolean = true;

console.log(`Meet ${robotName}, who is ${robotAge} years old. Friendly? ${isRobotFriendly}`); 
// Meet RoboCop, who is 100 years old. Friendly? true
Enter fullscreen mode Exit fullscreen mode

2. Array

TypeScript arrays can hold only one type of data:

let fruits: string[] = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

A cat organizing its toy collection (only balls):

let catToys: string[] = ["Ball1", "Ball2", "Ball3"];
console.log(catToys); // ["Ball1", "Ball2", "Ball3"]
Enter fullscreen mode Exit fullscreen mode

3. Tuple

Tuples allow you to express an array with a fixed number of elements whose types are known:

let myTuple: [string, number];
myTuple = ["Hello", 42]; // OK
console.log(myTuple); // ["Hello", 42]
Enter fullscreen mode Exit fullscreen mode

Imagine a super-secret agent with a codename and an ID number:

let agent: [string, number] = ["Bond", 007];
console.log(agent); // ["Bond", 007]
Enter fullscreen mode Exit fullscreen mode

Functions

TypeScript allows you to specify the types of parameters and return values of functions.

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

console.log(add(5, 3)); // 8
Enter fullscreen mode Exit fullscreen mode

A chef with a magic spoon:

function mixIngredients(ingredient1: string, ingredient2: string): string {
    return `${ingredient1} mixed with ${ingredient2}`;
}

console.log(mixIngredients("Flour", "Sugar")); // Flour mixed with Sugar
Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces define the structure of an object.

interface Person {
    name: string;
    age: number;
}

let user: Person = {
    name: "Alice",
    age: 30
};

console.log(user); // { name: "Alice", age: 30 }
Enter fullscreen mode Exit fullscreen mode

A talking dog with a special ID card:

interface Dog {
    name: string;
    breed: string;
}

let talkingDog: Dog = {
    name: "Scooby-Doo",
    breed: "Great Dane"
};

console.log(talkingDog); // { name: "Scooby-Doo", breed: "Great Dane" }
Enter fullscreen mode Exit fullscreen mode

Classes

TypeScript classes are a blueprint for creating objects with initial values and methods.

class Animal {
    name: string;

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

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

let dog = new Animal("Dog");
dog.move(10); // Dog moved 10 meters.
Enter fullscreen mode Exit fullscreen mode

A superhero class:

class Superhero {
    name: string;

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

    saveTheCat() {
        console.log(`${this.name} saved the cat!`);
    }
}

let hero = new Superhero("Batman");
hero.saveTheCat(); // Batman saved the cat!
Enter fullscreen mode Exit fullscreen mode

Enums

Enums allow us to define a set of named constants.

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Up;
console.log(move); // 0
Enter fullscreen mode Exit fullscreen mode

A traffic light system:

enum TrafficLight {
    Red,
    Yellow,
    Green
}

let light: TrafficLight = TrafficLight.Green;
console.log(light); // 2
Enter fullscreen mode Exit fullscreen mode

Conclusion

You've just had a whirlwind tour of TypeScript, from basic types to more advanced feature like enums. With these examples, you should have a good starting point to further explore and use TypeScript in your projects.

Feel free to ask if you have any specific questions or need more funny examples for any part of TypeScript!

Top comments (0)