返回

TypeScript 核心概念梳理

前端

TypeScript 核心概念梳理

变量

变量是 TypeScript 中用于存储数据的容器。变量可以存储各种类型的数据,包括数字、字符串、布尔值、数组和对象。变量必须先声明,然后才能使用。声明变量时,需要指定变量的名称和类型。例如:

let name: string = "John Doe";

类型

类型是 TypeScript 中用于定义变量和函数的类型。类型可以是基本类型或复合类型。基本类型包括数字、字符串、布尔值和 void。复合类型包括数组、对象和枚举。

类是 TypeScript 中用于创建对象的蓝图。类可以包含属性和方法。属性是类的成员变量,方法是类的成员函数。类可以通过 new 实例化,从而创建对象。例如:

class Person {
  name: string;
  age: number;

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

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

const person = new Person("John Doe", 30);
person.greet();

继承

继承是 TypeScript 中一种重要的面向对象特性。继承允许一个类从另一个类继承属性和方法。子类可以继承父类的所有非私有成员。例如:

class Employee extends Person {
  salary: number;

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

  getSalary() {
    return this.salary;
  }
}

const employee = new Employee("John Doe", 30, 10000);
console.log(employee.getSalary()); // 10000

多态

多态是 TypeScript 中另一种重要的面向对象特性。多态允许子类对象以不同方式响应相同的消息。例如,父类可以定义一个方法,子类可以重写该方法。当调用父类的方法时,实际调用的方法是子类重写的方法。例如:

class Animal {
  makeSound() {
    console.log("Animal sound");
  }
}

class Dog extends Animal {
  makeSound() {
    console.log("Woof!");
  }
}

class Cat extends Animal {
  makeSound() {
    console.log("Meow!");
  }
}

const animal = new Animal();
animal.makeSound(); // Animal sound

const dog = new Dog();
dog.makeSound(); // Woof!

const cat = new Cat();
cat.makeSound(); // Meow!

接口

接口是 TypeScript 中一种用于定义对象形状的工具。接口可以包含属性和方法的声明。接口不能被实例化,但它可以被类实现。当一个类实现了一个接口时,该类必须提供接口中声明的所有属性和方法。例如:

interface IAnimal {
  name: string;
  age: number;

  makeSound(): void;
}

class Dog implements IAnimal {
  name: string;
  age: number;

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

  makeSound() {
    console.log("Woof!");
  }
}

const dog = new Dog("Fido", 3);
console.log(dog.name); // Fido
console.log(dog.age); // 3
dog.makeSound(); // Woof!

泛型

泛型是 TypeScript 中一种用于创建可重用组件的工具。泛型允许函数和类接受类型参数。类型参数可以是任何类型,包括基本类型、复合类型和类型变量。例如:

function identity<T>(x: T): T {
  return x;
}

const number = identity(10); // number
const string = identity("Hello"); // string

模块

模块是 TypeScript 中用于组织代码的工具。模块可以包含变量、函数、类和接口。模块可以通过 import 关键字导入到其他模块中。例如:

// module.ts
export const name = "John Doe";

// main.ts
import { name } from "./module";

console.log(name); // John Doe

包是 TypeScript 中用于管理模块的工具。包可以包含多个模块。包可以通过 npm install 命令安装。例如:

npm install typescript

总结

本文对 TypeScript 核心概念进行了梳理,包括变量、类型、类、继承、多态、接口、泛型、模块和包等。通过对这些概念的理解,开发者可以更深入地掌握 TypeScript 这门语言,并编写出更健壮、更可维护的代码。