TypeScript 实践记录 | 青训营

23 阅读2分钟

在前端开发中,TypeScript已经成为了一种非常流行的语言,它为JavaScript提供了静态类型检查和更强大的面向对象编程能力。其中,类和泛型是TypeScript中非常重要的特性,能够帮助我们编写更具灵活性和安全性的代码。

🎯 1. 类的基本使用

在TypeScript中,我们可以使用class关键字来定义类。类是一种面向对象的编程概念,它可以包含属性和方法,并且可以通过实例化来创建对象。

下面是一个简单的示例,展示了如何定义一个类和使用它:

class Person {
  name: string;
  age: number;

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

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

const person = new Person('John', 25);
person.sayHello(); // 输出:Hello, my name is John and I'm 25 years old.

在上面的示例中,我们定义了一个Person类,它有两个属性nameage,以及一个方法sayHello。通过new关键字可以实例化一个Person对象,并调用sayHello方法。

🌈 2. 泛型的基本使用

泛型是TypeScript中非常强大的特性,它可以在编写可重用的代码时提供更大的灵活性。通过使用泛型,我们可以在定义类、函数或接口时延迟指定具体的类型,从而使代码更加通用。

下面是一个简单的示例,展示了如何使用泛型来创建一个可重用的数组类:

class MyArray<T> {
  private array: T[];

  constructor() {
    this.array = [];
  }

  push(item: T) {
    this.array.push(item);
  }

  pop(): T | undefined {
    return this.array.pop();
  }

  length(): number {
    return this.array.length;
  }
}

const numberArray = new MyArray<number>();
numberArray.push(1);
numberArray.push(2);
numberArray.push(3);
console.log(numberArray.length()); // 输出:3

const stringArray = new MyArray<string>();
stringArray.push('hello');
stringArray.push('world');
console.log(stringArray.pop()); // 输出:world

在上面的示例中,我们定义了一个MyArray类,它使用泛型T来表示数组中的元素类型。通过使用泛型,我们可以创建一个可重用的数组类,并在实例化时指定具体的类型。

🥰 3. 使用类型约束增加代码的灵活性和安全性

除了基本的泛型使用外,我们还可以使用类型约束来限制泛型的范围,从而增加代码的灵活性和安全性。

下面是一个示例,展示了如何使用类型约束来限制泛型类型必须具有特定的属性:

interface HasLength {
  length: number;
}

function printLength<T extends HasLength>(item: T) {
  console.log(item.length);
}

printLength('hello'); // 输出:5
printLength([1, 2, 3]); // 输出:3
printLength({ length: 10 }); // 输出:10
printLength(123); // 编译错误:类型"123"的参数不能赋给类型"HasLength"的参数

在上面的示例中,我们定义了一个HasLength接口,它要求具有length属性。然后,我们定义了一个printLength函数,它使用类型约束T extends HasLength来限制泛型类型必须实现HasLength接口。通过使用类型约束,我们可以在编译时捕获一些错误,提高代码的安全性。