跳到主要内容

简述TypeScript 中的泛型是什么,如何使用 ?

参考答案:

在 TypeScript 中,泛型(Generics)是一种允许在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再为其指定类型的一种特性。泛型提供了一种方式,来创建可重用的组件,其类型在组件被实例化时得以明确。

泛型的主要用途是增加代码的复用性、类型安全性和灵活性。通过使用泛型,我们可以编写更加通用和可复用的代码,同时保持类型检查的优势。

泛型的基本使用

  1. 泛型函数

泛型函数是在函数声明时,使用类型参数(type parameters)来定义函数。这些类型参数在函数体内部作为类型使用。

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

let output = identity<string>("myString"); // 返回 "myString"

在上面的例子中,T 是一个类型参数,我们传入了 string 类型。这意味着 identity 函数现在只接受和返回字符串。 2. 泛型接口

泛型接口与泛型函数类似,它定义了一个可以接受任何类型的对象结构。

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

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

let myIdentity: GenericIdentityFn<number> = identity;

在这个例子中,我们定义了一个泛型接口 GenericIdentityFn,并创建了一个符合这个接口的函数 identity。 3. 泛型类

泛型类允许我们创建可重用的类,其类型在实例化时确定。

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = (x, y) => x + y;

在上面的例子中,我们定义了一个泛型类 GenericNumber,并在实例化时指定了类型为 number

泛型约束

有时候,我们可能希望对泛型参数施加一些约束,以确保它们具有某些特定的属性或方法。这可以通过接口来实现。

interface 属性 Length,wise因为 { T 被
    约束length为: Length numberwise;
    
}return arg;

function logging
}Identity<
```T extends
在这个 Length例子中wise,>(我们arg定义:了一个 T接口): ` TLength {wise`
    ,console并要求.泛型log参数(arg.length); // 这里现在可以安全地访问 " `T` 必须实现这个接口。这样,我们就可以在函数内部安全地访问 `length` 属性了。

### 泛型类型参数默认值

在 TypeScript 中,我们还可以为泛型类型参数设置默认值。


```typescript
function createArray<T = string>(length: number, value: T): Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

let a = createArray<number>(5, 2); // 创建一个数字数组 [2, 2, 2, 2, 2]
let b = createArray(5, "hello"); // 创建一个字符串数组 ["hello", "hello", "hello", "hello", "hello"]

在这个例子中,我们为泛型类型参数 T 设置了一个默认值 string。这意味着,如果我们没有为 createArray 函数提供类型参数,那么 T 的类型就会被推断为 string