首页 > 解决方案 > 打字稿,定义一个通用的代替对象

问题描述

目前我有这个接口:

export interface requestPayload {
  agentId: string;
}

export interface Agent {
  id: string;
  name: string;
  requestPayload: requestPayload;
}

我的问题是接口的requestPayload属性Agent现在是一个对象{ agentId: string; }

requestPayload应该是任何东西,比如数组、数字、字符串,也许还有我用requestPayload接口定义的那个对象。

我收到了“使用泛型”的建议,如何将其更改为泛型?我不确定如何进行。

标签: typescripttypescript-generics

解决方案


对于您的情况,使用泛型是非常正确的解决方案:

export interface Agent<T> {
  id: string;
  name: string;
  requestPayload: T;
}

推荐阅读