Home > Web Front-end > JS Tutorial > body text

Introduction to TypeScript

王林
Release: 2024-07-24 14:49:19
Original
239 people have browsed it

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

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

tsc filename.ts
Copy after login

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

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
Copy after login

2. Array

TypeScript arrays can hold only one type of data:

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

A cat organizing its toy collection (only balls):

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

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]
Copy after login

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

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

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
Copy after login

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
Copy after login

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 }
Copy after login

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" }
Copy after login

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.
Copy after login

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!
Copy after login

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
Copy after login

A traffic light system:

enum TrafficLight {
    Red,
    Yellow,
    Green
}

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

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!