You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使TypeScript的QueryParams类包含泛型T的键成员?

解决方案

在TypeScript中,你可以让QueryParams类实现Partial<T>来自动获取泛型T的所有可选属性,同时保留page这类固定成员,具体实现如下:

class QueryParams<T> implements Partial<T> {
  page?: number;
  // 可在此添加其他固定属性,比如size、sort等
}

// 测试实体类
class AnotherEntity {
  prop_1: string;
  prop_2: number;
  prop_3: string;
}

// 使用示例
const query: QueryParams<AnotherEntity> = {};
query.prop_1 = "demo"; // 合法
query.prop_2 = 456; // 合法
query.page = 2; // 合法

原理说明

  • Partial<T>是TypeScript内置工具类型,它会把泛型T的所有属性转换为可选类型。
  • 通过implements Partial<T>,QueryParams类会自动继承T的所有可选属性,无需手动逐个声明。
  • 类中定义的page等固定属性,会和T的属性合并到最终的实例类型中。

内容的提问来源于stack exchange,提问作者mehayoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:39:57