typescript 泛型
发布日期:2021-05-08 06:36:20 浏览次数:20 分类:精选文章

本文共 1765 字,大约阅读时间需要 5 分钟。

泥潭泛型概述

泛型(Generic)是一种强大的TypeScript功能,能够在代码中定义通用类型,而不仅仅针对特定的数据类型。通过泛型,我们可以创造灵活且可扩展的代码,适用于多种场景。

泥潭泛型基础

在TypeScript中,泛型的基本用途是定义一个可以接受任意类型参数的函数或对象。这意味着我们可以在调用函数或使用对象时,传入特定的类型参数,从而实现类型安全的代码。

例如,以下函数ex可以接受任意类型的参数T,并返回相同类型的值:

function ex
(arg: T): T {
console.log(arg);
return arg;
}

调用时可以传入不同的类型参数:

ex
(1); // 返回类型为number
ex
('string');

如果不传参数,TypeScript会默认使用any类型:

ex(456);
ex('1444');

泥潭泛型结合类型定义

有时,我们需要定义复杂的类型结构,并结合泛型使用。例如,可以定义一个包含多个类型字段的结果类型resultType

type resultType
= {
a: string;
b: number;
c: T;
};
const extd: resultType
= {
a: 'fd',
b: 1,
c: 1
};
const extf: resultType<() => void> = {
a: 'dx',
b: 18,
c: () => {
console.log(a);
}
};

通过自定义类型Ttype,我们可以将泛型T设置为特定的类型:

type Ttype = {
f: boolean;
g: any;
};
const exth: resultType
= {
a: 'yx',
b: 18,
c: {
f: false,
g: 'any'
}
};

泥潭泛型类

泛型类是将泛型应用于类实例和方法的一种高级用法。例如,定义一个通用的容器类MainClass,其中允许存储任意类型的元素。

class MainClass
{
public list: T[] = [];
add(value: T): void {
this.list.push(value);
}
show(): T[] {
return this.list;
}
}
const main1 = new MainClass
();
main1.add(1);
main1.add(2);
// 由于T被设置为number,传入的值必须是number类型
main1.add('dfahkj'); // 会报类型错误
const main2 = new MainClass<{a: string; b: number}>();
main2.add({a: 'dx', b: 18});
main2.add({a: 'yx', b: 16});
console.log(main2.show()); // [{a:'dx',b:18},{a:'yx',b:16}]

泥潭泛型接口

泛型接口是泛型的另一种应用形式,用于定义对象的公共方法和属性的类型结构。例如,定义一个通用的接口ExInterface,其中包含三个字段和一个方法。

interface ExInterface
{
a: string;
b: number;
c: T;
}
const ExInterface1: ExInterface
= {
a: 'dx',
b: 18,
c: 16
};

通过这种方式,我们可以创建灵活且可扩展的代码结构。

上一篇:typescript class可以作为类型定义被扩展
下一篇:NPM 依赖库版本号、符号

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年03月21日 08时20分44秒