Vue3.3 + TS4,自主打造媲美 ElementPlus 的组件库
泛型第三部分 – 泛型在类和接口中的使用
在面向对象编程中,泛型允许你在定义类、接口和方法时使用类型参数,从而提高代码的复用性和类型安全性。接下来,我们将详细介绍如何在类和接口中使用泛型。
泛型类是在类定义中包含一个或多个类型参数的类。通过使用泛型类,你可以编写适用于多种类型的代码,而无需为每种类型编写单独的实现。
typescript深色版本class GenericClass<T> { private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } setValue(value: T): void { this.value = value; }}
在这个例子中,GenericClass
是一个泛型类,它接受一个类型参数 T
。这个类有一个私有属性 value
,其类型由 T
决定。getValue
和 setValue
方法用于获取和设置该值。
你可以指定具体的类型来实例化泛型类:
typescript深色版本const numberInstance = new GenericClass<number>(10);console.log(numberInstance.getValue()); // 输出 10const stringInstance = new GenericClass<string>("Hello, World!");console.log(stringInstance.getValue()); // 输出 "Hello, World!"
泛型接口与泛型类类似,可以在接口定义中包含类型参数。这使得接口可以适用于多种类型。
typescript深色版本interface GenericInterface<T> { value: T; setValue(newValue: T): void; getValue(): T;}
这个接口定义了一个具有 value
属性的对象,并提供了 setValue
和 getValue
方法来操作该属性。
你可以创建一个类来实现泛型接口,并指定具体的类型:
typescript深色版本class ImplementingClass<T> implements GenericInterface<T> { value: T; constructor(value: T) { this.value = value; } setValue(newValue: T): void { this.value = newValue; } getValue(): T { return this.value; }}const instance = new ImplementingClass<number>(20);console.log(instance.getValue()); // 输出 20instance.setValue(30);console.log(instance.getValue()); // 输出 30
有时你可能希望对泛型的类型参数施加一些限制。例如,你可能希望某个类型参数必须实现某个接口或者继承自某个基类。这时可以使用泛型约束。
typescript深色版本interface Lengthwise { length: number;}function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg;}// 正确使用loggingIdentity("Hello, World!"); // 输出 13// 错误使用,因为 number 类型没有 length 属性// loggingIdentity(42); // 编译错误
在这个例子中,loggingIdentity
函数要求传入的参数必须是实现了 Lengthwise
接口的类型(即具有 length
属性)。
泛型不仅可以有一个类型参数,还可以有多个。你可以根据需要定义任意数量的类型参数。
typescript深色版本class MultiTypeGenericClass<K, V> { private key: K; private value: V; constructor(key: K, value: V) { this.key = key; this.value = value; } getKey(): K { return this.key; } getValue(): V { return this.value; } setKey(key: K): void { this.key = key; } setValue(value: V): void { this.value = value; }}const instance = new MultiTypeGenericClass<string, number>("id", 123);console.log(instance.getKey()); // 输出 "id"console.log(instance.getValue()); // 输出 123
在这个例子中,MultiTypeGenericClass
接受两个类型参数 K
和 V
,分别用于键和值的类型。
通过合理使用泛型,你可以编写出更加通用、灵活且类型安全的代码。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。