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

TypeScript泛型接口属性访问函数类型推导问题求助

TypeScript泛型函数自动推导返回类型问题

需要接收两组命令行参数描述两个独立的数据库连接,为避免代码重复,将连接参数的接口定义为泛型类型。目前已完成泛型接口定义,但编写访问该接口属性的泛型函数时遇到问题:

  • 第一种写法返回类型不符合预期
  • 第二种写法无法编译

希望找到能让代码自动推导返回类型的解决方案,无需手动指定返回类型。

相关代码

泛型接口定义

interface BasePosgresProgramOptions {
  postgresConnectionString?: string;
  postgresSrvServiceName?: string;
  postgresDb?: string;
  postgresDbFile?: string;
  postgresUser?: string;
  postgresUserFile?: string;
  postgresPassword?: string;
  postgresPasswordFile?: string;
  postgresHost?: string;
  postgresPoolMax?: number;
  postgresPort?: number;
  postgresSslCaFile?: string;
}

type ConnectionNames = "" | "Secondary";

export type PosgresProgramOptions<Suffix extends ConnectionNames> = {
  [k in keyof BasePosgresProgramOptions as `${k}${Suffix}`]: BasePosgresProgramOptions[k];
};

最初的函数写法(返回类型不符合预期)

export const getPostgresOption = <Suffix extends ConnectionNames>(
  args: PosgresProgramOptions<Suffix> | undefined,
  suffix: Suffix,
  option: keyof BasePosgresProgramOptions
) => args?.[`${option}${suffix}`];

尝试改进的写法(无法编译)

export const getPostgresOption = <Suffix extends ConnectionNames, Option extends keyof BasePosgresProgramOptions>(
  args: PosgresProgramOptions<Suffix> | undefined,
  suffix: Suffix,
  option: Option
) => args?.[`${option}${suffix}`];

解决方案

问题核心是TypeScript无法自动将${Option}${Suffix}的拼接结果识别为PosgresProgramOptions<Suffix>的合法键类型,导致类型推导失败。可以通过类型断言结合辅助类型让TypeScript建立键与属性类型的关联,从而自动推导返回类型:

// 辅助类型:定义带后缀的键类型
type KeyWithSuffix<Suffix extends ConnectionNames, Option extends keyof BasePosgresProgramOptions> = `${Option}${Suffix}`;

export const getPostgresOption = <Suffix extends ConnectionNames, Option extends keyof BasePosgresProgramOptions>(
  args: PosgresProgramOptions<Suffix> | undefined,
  suffix: Suffix,
  option: Option
) => {
  // 将拼接后的字符串断言为合法键类型
  const key = `${option}${suffix}` as KeyWithSuffix<Suffix, Option>;
  return args?.[key];
};

此时TypeScript会自动推导返回类型为BasePosgresProgramOptions[Option] | undefined,完全符合预期,无需手动指定返回类型。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:04:58