首页 > 解决方案 > TypeScript:使用通用扩展?

问题描述

问题:

我试图弄清楚是否可以扩展泛型。

API 的项目和响应

我正在使用具有多种类型项目的 API 服务,例如,如果项目类型为User

interface IUser {
  email: string;
  id: string;
  displayName: string;
}

当从 API 请求特定项目时,响应是,例如,对于User

interface IUserResponse {
  '@odata.context': string;
  email: string;
  id: string;
  displayName: string;
}

当从 API 请求项目列表时,响应是,例如,对于User

interface IUserResponseArray {
  '@odata.context': string;
  value: [ {
      email: string;
      id: string;
      displayName: string;
    },
    ...
  ]
}

IUserAPI 对[非通用]的响应

采取这两个响应,都具有以下基础:

interface IResponseBase {
  '@odata.context': string;
}

从这个基础扩展,IUser响应接口重构:

interface IUserResponse extends IUser, IResponseBase {}

interface IUserResponseArray extends IResponseBase {
  value: IUser[]
}

API 的响应泛型

其次,因为这个 API 支持多种类型的项目,所以响应接口应该是通用的。

做一系列通用项目,使IUserResponseArray通用:

interface IResponseArray<T> extends IResponseBase {
  value: T[];
}

问题type name expected

我怎样才能做到IUserResponse通用。以下定义泛型的尝试无效,来自我的 IDE 的错误提示是type name expected

interface IResponse<T> extends ???<T>???, IResponseBase {}

标签: typescriptgenerics

解决方案


推荐阅读