TypeScript 泛型与类型约束| 豆包MarsCode AI刷题

39 阅读2分钟

TypeScript 泛型与类型约束

一、泛型使用方法

在 TypeScript 中,泛型允许我们编写可复用且能适应多种类型的代码。例如定义一个函数,它可以操作不同类型的数据:

typescript

function identity(arg: T): T { return arg; } // 使用时指定类型 let output1 = identity("hello"); // 也可由编译器自动推断类型 let output2 = identity(123);  

这里的    就是泛型类型参数, T  可以代表任意类型,在函数定义时使用它作为参数类型和返回值类型,使得函数具有通用性。

类也可以使用泛型:

typescript

class GenericClass { private value: T; constructor(val: T) { this.value = val; } getValue(): T { return this.value; } } let instance = new GenericClass(5);  

二、泛型使用场景

1. 数据结构与算法:如创建通用的列表、队列、栈等数据结构。例如,一个简单的数组包装类:

typescript

class ArrayWrapper { private data: T[] = []; add(item: T): void { this.data.push(item); } get(index: number): T { return this.data[index]; } }  

2. 函数库开发:编写能处理多种类型的工具函数,像处理不同类型数组的排序函数等。

三、类型约束

为了增加代码的灵活性和安全性,我们可以对泛型添加类型约束。使用  extends  关键字:

typescript

interface Lengthwise { length: number; } function loggingIdentity(arg: T): T { console.log(arg.length); return arg; } // 正确,因为数组有 length 属性 loggingIdentity([1, 2, 3]); // 错误,普通数字没有 length 属性 loggingIdentity(5);  

这样就确保了传入  loggingIdentity  函数的参数必须具有  length  属性,既保证了函数内代码的安全性(不会访问不存在的属性),又在一定程度上灵活地允许多种符合条件的类型(如数组、字符串等)使用该函数。

通过合理使用泛型和类型约束,TypeScript 代码能够在保持类型安全的同时,更好地复用逻辑,适应不同的数据类型和业务场景,提升代码质量与开发效率,减少因类型不匹配导致的错误。