Skip to content

泛型

TypeScript 中的泛型是指在定义函数、接口或类时,不预先指定具体的类型,而是在使用时再指定具体的类型。

泛型的基本使用

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

const result1 = identity(123); // result1: number
const result2 = identity('hello'); // result2: string
const result3 = identity(true); // result3: boolean

泛型变量

typescript
function identity<T extends string | number | boolean>(arg: T): T {
    return arg;
}

const result1 = identity(123); // result1: number
const result2 = identity('hello'); // result2: string
const result3 = identity(true); // result3: boolean
const result4 = identity(null); // error: null is not a string | number | boolean

泛型函数

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

function repeat<T extends string | number | boolean>(str: T, count: number): T {
    let result = '';
    for (let i = 0; i < count; i++) {
        result += str;
    }
    return result as T;
}

const result1 = repeat('hello', 3); // result1: string
const result2 = repeat(123, 4); // result2: number
const result3 = repeat(true, 2); // result3: boolean

泛型接口

typescript
interface IArray<T> {
    push(value: T): void;

    pop(): T | undefined;
}

function createArray<T>(): IArray<T> {
    const arr: T[] = [];
    return {
        push(value: T) {
            arr.push(value);
        },
        pop() {
            return arr.pop();
        }
    };
}

const arr1 = createArray<number>();
arr1.push(1);
arr1.push(2);
arr1.push(3);
console.log(arr1.pop()); // 3

const arr2 = createArray<string>();
arr2.push('hello');
arr2.push('world');
arr2.push('!');
console.log(arr2.pop()); // !

泛型类

typescript
class MyClass<T> {
    constructor(public value: T) {
    }
}

const obj1 = new MyClass<number>(123);
const obj2 = new MyClass<string>('hello');
const obj3 = new MyClass<boolean>(true);

泛型约束

typescript
function identity<T extends string | number | boolean>(arg: T): T {
    return arg;
}

function repeat<T extends string | number | boolean>(str: T, count: number): T {
    let result = '';
    for (let i = 0; i < count; i++) {
        result += str;
    }
    return result as T;
}

const result1 = repeat('hello', 3); // result1: string
const result2 = repeat(123, 4); // result2: number
const result3 = repeat(true, 2); // result3: boolean
const result4 = repeat(null, 2); // error: null is not a string | number | boolean