You need to enable JavaScript to run this app. TypeScript基于参数可选属性定义条件返回类型的d.ts编写问题
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript基于参数可选属性定义条件返回类型的d.ts编写问题

解决方案

你可以通过交叉类型将每个重载的特定属性约束和完整的QueryOptions结合,同时保留你原有的undefined兼容逻辑,调整后的类型声明如下:

export interface Character {
  // 此处为你的Character类型原有定义
}

export interface QueryOptions {
  matchAliases?: boolean;  // default true
  matchCategories?: boolean;  // default false
  verboseCategories?: boolean;  // default false
}

export interface QueryFunction<Result> {
  // 检索名称列表:matchCategories为true,verboseCategories为false/不传
  (query: "names", opts?: QueryOptions & { matchCategories: true; verboseCategories?: false; }): string[];
  // 检索名称列表:matchCategories和verboseCategories都为true
  (query: "names", opts?: QueryOptions & { matchCategories: true; verboseCategories: true; }): Result[];

  // 匹配单个结果:matchCategories为false/不传
  (query: string, opts?: QueryOptions & { matchCategories?: false | undefined; }): Result | undefined;

  // 可能返回多个结果:matchCategories为true,verboseCategories为false/不传
  (query: string, opts?: QueryOptions & { matchCategories: true; verboseCategories?: false; }): Result | string[] | undefined;
  // 可能返回多个结果:matchCategories和verboseCategories都为true
  (query: string, opts?: QueryOptions & { matchCategories: true; verboseCategories: true; }): Result | Result[] | undefined;
}

export const characters: QueryFunction<Character>;

逻辑说明

  • 交叉类型QueryOptions & { 特定约束 }既允许传入QueryOptions定义的所有可选属性(比如matchAliases),又能限定当前重载下影响返回类型的属性的取值,不会漏掉其他参数的类型校验。
  • 你原有对默认值的兼容逻辑已经正确:把可选属性的undefined类型和默认值的类型合并(比如matchCategories?: false | undefined),就能匹配用户不传该属性的场景,和运行时的默认值逻辑完全对应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:27:03