javascript - Typescript 中泛型的常见用法是什么?
问题描述
我试图了解 Typescript 泛型在现实生活中的常用案例,而不是小众案例。我知道它为函数/类/接口添加了额外的抽象层,以便它们可以在不同的情况下重用,但我觉得您通常可以使用联合和交集类型来适应一定程度的通用性。
但是,举个例子:
interface Identities<V, W> {
id1: V,
id2: W
}
function identities<T, U> (arg1: T, arg2: U): Identities<T, U> {
let identities: Identities<T, U> = {
id1: arg1,
id2: arg2
};
return identities;
}
所有这些都确保无论参数具有什么类型,返回值都必须与类型匹配。
我可以想象如果您希望您的函数/类能够容纳各种不同的参数,但您唯一的限制是它们必须与某些方法兼容:
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;
}
这在某些情况下使用。
解决方案
泛型可用于存储来自 API 调用的附加数据,例如:
API 响应:
value: {} // this is generic
messages: [] // additional logging/errors/warnings
// other properties that apply for all objects
打字稿:
export interface GenericResponse<T> {
value: T;
messages: ApiMessageItem[];
// additional properties
}
其中 T 是我从 API 调用的任何对象。
你仍然可以使用 Unions 来做到这一点,但我认为使用泛型更简洁,尤其是使用 50 个不同的 API 对象。
推荐阅读
- python - 如何安装蟒蛇 Python
- java - R.java 文件丢失/未在 android studio 中生成
- r - R 中德语变音符号 ä、ö、ü 和 ß 的编码问题
- merge - 检查 Stylecop 警告是否已减少
- sql - 在 RDB 中设计一个表来销售多个项目,并计算销售的价值
- c# - 如何在 .editorconfig 的 CSharp 编辑器的嵌套范围内更喜欢完全限定的“使用名称”
- google-cloud-platform - Dataprep 配方无法加载“无法读取未定义的属性‘expandScriptLines’”
- jmeter - JMeter 等待页面完全加载
- jquery - JQuery 2-modal 冲突:需要“删除”animatedModal,但要使用 DELAY,以隐藏第二个模态的滚动条
- postgresql - 在postgresql中加入删除