TypeScript基础--泛型

泛型的意义:在软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑吧可重用性。组件不仅能够支持当前的数据类型,同时也要支持未来的数据类型。

TypeScript的泛型示例:

  1. 泛型定义
function identity<T>(arg: T): T {
    return arg;
}
  1. 泛型接口示例
interface GenericIdentityFn<T> {
    (arg: T): T;
}
function identity<T>(arg: T): T {
    return arg;
}
let myIdentity: GenericIdentityFn<number> = identity;
  1. 泛型类示例
class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

泛型约束

function loggingIdentity<T>(arg: T): T {
    console.log(arg.length);  // Error: T doesn't have .length
    return arg;
}

上面这个例子中,编译器会直接报错。原因很简单,实际在确定泛型类型的时候,我们并不能保证每种数据类型都有length属性。

前面学习过,TypeScript接口可以用来表示契约(约束),所有我们可以修改为如下方式:

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);  // Now we know it has a .length property, so no more error
    return arg;
}

正确的调用方式如下:

loggingIdentity({ length: 10, value: 3 });
loggingIdentity("12345");
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容