TypeScript 中的泛型是什么?如何使用它们?
时间: 2023-12-06 09:45:11 浏览: 43
泛型是 TypeScript 的一种特性,它允许在定义函数、类、接口等时使用类型参数,在使用时再确定具体的类型。这样可以增强代码的灵活性和重用性。
使用泛型的语法是在定义函数、类、接口等时在参数或返回值的类型前使用尖括号 `<>` 来定义类型参数。例如:
```typescript
function identity<T>(arg: T): T {
return arg;
}
```
上述代码中,`<T>` 定义了一个类型参数 `T`,`arg` 参数的类型为 `T`,返回值的类型也为 `T`。
使用时,需要指定具体的类型。例如:
```typescript
let output = identity<string>("hello world");
```
在这个例子中,我们将 `identity` 函数的类型参数 `T` 指定为 `string`,这样 `arg` 参数和返回值的类型都会是 `string`。
当然,TypeScript 也支持类型推断,可以根据传入的参数自动推断类型参数。例如:
```typescript
let output = identity("hello world");
```
因为传入的参数是 `string` 类型,TypeScript 会自动推断出类型参数 `T` 为 `string`,所以不需要显式指定类型参数。
除了函数,泛型还可以应用于类和接口的定义中。例如:
```typescript
interface List<T> {
add(item: T): void;
get(index: number): T;
}
class ArrayList<T> implements List<T> {
private items: T[] = [];
add(item: T) {
this.items.push(item);
}
get(index: number): T {
return this.items[index];
}
}
```
上述代码中,`List` 接口和 `ArrayList` 类都使用了类型参数 `T`,`ArrayList` 类实现了 `List` 接口,并且在实现接口中明确了类型参数的类型。这样,当使用 `ArrayList` 类时,也需要指定类型参数的具体类型。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)