TypeScript 类、泛型的使用实践记录 | 青训营

47 阅读1分钟

类的基本定义与使用

首先,让我们回顾一下如何在 TypeScript 中定义和使用类:

typescriptCopy code
class Animal {
  name: string;

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

  makeSound() {
    console.log(`${this.name} makes a sound`);
  }
}

const dog = new Animal("Dog");
dog.makeSound(); // Output: "Dog makes a sound"

泛型的基本使用方法

接下来,让我们了解如何在 TypeScript 中使用泛型来增加代码的灵活性。泛型允许我们编写可以适用于不同类型的代码。

typescriptCopy code
class Box<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }
}

const numberBox = new Box(42);
const stringBox = new Box("Hello");

console.log(numberBox.value); // Output: 42
console.log(stringBox.value); // Output: "Hello"

使用泛型约束

泛型约束允许我们限制泛型类型的范围,以确保代码的类型安全性。这在处理特定类型或具有特定属性的对象时非常有用。

typescriptCopy code
interface Lengthy {
  length: number;
}

function printLength<T extends Lengthy>(item: T) {
  console.log(`Length: ${item.length}`);
}

printLength("Hello");           // Output: Length: 5
printLength([1, 2, 3]);         // Output: Length: 3
printLength({ length: 10 });    // Output: Length: 10
// printLength(42);             // 编译错误,number 没有 length 属性

在类中使用泛型

在类中使用泛型可以使类更具通用性。例如,我们可以创建一个泛型的堆栈类:

typescriptCopy code
class Stack<T> {
  items: T[] = [];

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

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

const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop()); // Output: 2

const stringStack = new Stack<string>();
stringStack.push("a");
stringStack.push("b");
console.log(stringStack.pop()); // Output: "b"

总结

在 TypeScript 中,使用类和泛型的实践可以使您的代码更具可维护性和灵活性。通过泛型,您可以编写适用于多种类型的通用代码,同时通过泛型约束,您可以增加代码的类型安全性。类和泛型的结合使用可以帮助您创建更具表现力和可复用性的代码。无论是创建通用的数据结构还是处理不同类型的数据,都可以借助 TypeScript 的类和泛型功能来实现这些目标。