Home  >  Article  >  Web Front-end  >  Introduction to TypeScript

Introduction to TypeScript

王林
王林Original
2024-07-24 14:49:19411browse

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
  1. Initialize a TypeScript project:
tsc --init
  1. Compile TypeScript:

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

tsc filename.ts

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!
  • Number
let age: number = 42;
console.log(`I'm ${age} years old!`); // I'm 42 years old!
  • Boolean
let isHappy: boolean = true;
console.log(`Am I happy? ${isHappy}`); // Am I happy? true

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

2. Array

TypeScript arrays can hold only one type of data:

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

A cat organizing its toy collection (only balls):

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

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]

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

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

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

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

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 }

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" }

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.

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!

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

A traffic light system:

enum TrafficLight {
    Red,
    Yellow,
    Green
}

let light: TrafficLight = TrafficLight.Green;
console.log(light); // 2

Conclusion

_You've just had a whirlwind tour of TypeScript, from basic types to more advanced features like generics and 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!_

The above is the detailed content of Introduction to TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn