TypeScript中类与泛型的使用场景 | 青训营

70 阅读3分钟

类与泛型的使用场景

TypeScript作为JavaScript的超集,提供了类(Class)和泛型(Generic)等面向对象和泛型编程的特性。类是一种面向对象的特性,用于封装数据和方法,而泛型是一种允许在定义函数、接口或类时使用类型参数的技术。本文将结合实际代码案例,介绍TypeScript中类与泛型的使用场景。

类的使用场景

封装数据和方法

类用于定义对象模版,通过封装数据和方法,可以实现模块化和信息隐藏。以下是一个示例:

class Circle {
  public radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }

  public getDiameter(): number {
    return 2 * this.radius;
  }
}

const circle = new Circle(5);
console.log(circle.getDiameter()); // 输出10

在这个例子中,我们定义了一个名为Circle的类,包含一个属性radius和一个方法getDiameter。通过类的封装,我们可以将半径和相关的计算逻辑封装在一起,方便使用和维护。

继承和多态

类支持继承和多态,允许我们创建可重用的代码和灵活的设计。以下是一个示例:

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

  public getName(): string {
    return this.name;
  }
}

class Circle extends Shape {
  public radius: number;
  constructor(radius: number, name: string) {
    super(name);
    this.radius = radius;
  }

  public getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

const circle = new Circle(5, 'circle');
console.log(circle.getName()); // 输出circle
console.log(circle.getArea()); // 输出78.***

在这个例子中,我们定义了一个名为Shape的父类,包含了一个getName方法。Circle类继承了Shape类,并添加了一个radius属性和一个getArea方法。通过继承,Circle可以重用Shape的代码,并添加自己的特性。

泛型的使用场景

增强函数复用性

泛型允许我们在定义函数、接口或类时使用类型参数,从而增强函数复用性。以下是一个示例:

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

const outputString = identity<string>('hello'); // 输出'hello'
const outputNumber = identity<number>(42); // 输出42

在这个例子中,我们定义了一个名为identity的泛型函数,该函数接收一个类型为T的参数并返回相同类型的值。通过使用泛型,我们可以使用相同的函数处理不同类型的数据。

自定义泛型接口

泛型不仅可以用于函数,还可以用于接口。以下是一个示例:

interface GenericIdentityFn<T> {
  (arg: T): T;
}

const identityNumber: GenericIdentityFn<number> = (num) => num;
const identityString: GenericIdentityFn<string> = (str) => str;

在这个例子中,我们定义了一个名为GenericIdentityFn的泛型接口,该接口描述了一个接受类型为T的参数并返回相同类型的值的函数。通过实现这个接口,我们可以为不同类型定义特定的函数。

总而言之,TypeScript类用于封装数据和方法,支持继承和多态,有助于模块化和代码重用。泛型允许我们在定义函数、接口或类时使用类型参数,增强函数复用性,并支持自定义泛型接口。在实际开发中,结合类和泛型的使用场景,我们可以编写出更灵活、可重用的代码。