TypeScript 泛型语法

49 阅读1分钟

TypeScript 中的泛型(Generics)是一种编程特性,使你能够编写更灵活和可复用的函数、类和接口,因为它们可以在编写时不指定具体的数据类型,而是在使用时根据传入的参数类型自动确定。

泛型函数

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

// 使用泛型函数
let result = identity<string>("Hello, TypeScript");
console.log(result); // 输出 "Hello, TypeScript"

泛型接口

typescriptCopy code
interface Pair<T, U> {
    first: T;
    second: U;
}

// 使用泛型接口
const pair: Pair<number, string> = { first: 1, second: "two" };
console.log(pair.first); // 输出 1
console.log(pair.second); // 输出 "two"

泛型类

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

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

    getValue(): T {
        return this.value;
    }
}

// 使用泛型类
const boxOfString = new Box<string>("Hello");
console.log(boxOfString.getValue()); // 输出 "Hello"

const boxOfNumber = new Box<number>(42);
console.log(boxOfNumber.getValue()); // 输出 42