首页 > 解决方案 > 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;
}

这在某些情况下使用。

标签: javascripttypescripttypescript-generics

解决方案


泛型可用于存储来自 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 对象。


推荐阅读