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

99 阅读2分钟

#青训营笔记创作活动在 TypeScript 中,泛型是一种强大的工具,可以使你的代码更具灵活性和安全性。它允许你编写能够适用于不同类型的数据的通用代码。以下是一些关于 TypeScript 类和泛型的使用实践记录,涵盖了泛型的使用方法、场景以及如何使用类型约束来提高代码的灵活性和安全性。

泛型基础

首先,让我们回顾一下 TypeScript 泛型的基础知识。泛型允许你在定义函数、类、接口等时使用一个占位符来表示某个具体类型,以便在使用时指定实际类型。这样可以让你的代码更具通用性和可复用性。

1. 泛型函数示例:

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

const result = identity<string>("Hello, TypeScript!");
console.log(result); // Output: Hello, TypeScript!

2. 泛型类示例:

class Box<T> {
    value: T;

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

const numberBox = new Box<number>(42);
const stringBox = new Box<string>("TypeScript");

泛型的使用场景

泛型在很多场景下都能发挥作用,特别是在与集合、数据结构、函数式编程等相关的领域。

1. 集合类的泛型使用:

class List<T> {
    private items: T[] = [];

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

    getAll(): T[] {
        return this.items;
    }
}

const numberList = new List<number>();
numberList.add(1);
numberList.add(2);
console.log(numberList.getAll()); // Output: [1, 2]

const stringList = new List<string>();
stringList.add("hello");
stringList.add("world");
console.log(stringList.getAll()); // Output: ["hello", "world"]

2. 函数式编程中的泛型应用:

function mapArray<T, U>(array: T[], callback: (item: T) => U): U[] {
    return array.map(callback);
}

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = mapArray(numbers, num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

类型约束增加灵活性和安全性

类型约束是一种使用泛型的重要方式,它允许你对泛型的类型范围进行限制,从而在编译时捕获潜在的类型错误。

1. 使用 extends 关键字进行类型约束:

interface Lengthwise {
    length: number;
}

function getLength<T extends Lengthwise>(obj: T): number {
    return obj.length;
}

const strLength = getLength("hello");
const arrLength = getLength([1, 2, 3]);
console.log(strLength); // Output: 5
console.log(arrLength); // Output: 3

2. 泛型类类型约束示例:

interface Shape {
    area(): number;
}

class Circle implements Shape {
    constructor(private radius: number) {}

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

class Square implements Shape {
    constructor(private sideLength: number) {}

    area(): number {
        return this.sideLength ** 2;
    }
}

function calculateTotalArea<T extends Shape>(shapes: T[]): number {
    return shapes.reduce((total, shape) => total + shape.area(), 0);
}

const shapes: Shape[] = [new Circle(5), new Square(4)];
const totalArea = calculateTotalArea(shapes);
console.log(totalArea); // Output: Approximately 81.42

通过这些实践记录,你可以更好地理解 TypeScript 中的泛型如何应用于类和函数,以及如何使用类型约束来提高代码的灵活性和安全性。泛型使你能够创建更具通用性和可复用性的代码,同时通过类型约束,你可以在编译时捕获潜在的类型错误,从而增加代码的可维护性和健壮性。