首页 > 解决方案 > 如何创建一个泛型类型,它是 TypeScript 中其他类型的组合?

问题描述

假设我想创建一个UserResponse看起来像这样的类型:

type UserResponse = {
  data: User,
  meta: Meta
}

我怎样才能使Response类型更通用,以便我不必为只有data属性类型更改的其他响应类型重新创建相同的结构?

因此,创建一个新类型将如下所示:

type ArticleResponse = Response<Article>

标签: typescripttypes

解决方案


就这么简单:

interface Response<T> {
    data: T,
    meta: Meta
}

type ArticleResponse = Response<Article>;
type UserResponse = Response<User>;

推荐阅读