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

TypeScript如何推导泛型类型的成员函数返回类型

解决方案

你可以通过 TypeScript 内置的类型工具实现和 C++ decltype 等价的类型推导逻辑,核心用到 ReturnType<> 提取函数返回值类型,再用 Awaited<> 拆解 Promise 包裹的类型。

优化后代码

// 定义通用 Partial 基础接口
interface PartialBase {
  partial: boolean;
  fetch(): Promise<unknown>;
}

// 自动推导返回类型
async function departialize<T extends PartialBase>(thing: T): Promise<Awaited<ReturnType<T['fetch']>>> {
  if (thing.partial) {
    return await thing.fetch();
  } else {
    // 因为完整类型本身和 fetch 返回类型一致,直接断言即可
    return thing as Awaited<ReturnType<T['fetch']>>;
  }
}

效果说明

当你传入 Discord.User | Discord.PartialUser 类型的参数时,函数返回值会自动推导为 Promise<Discord.User>,完全符合需求。该实现对所有 discord.js 内的 Partial 类型(比如 PartialGuild、PartialMessage 等)都通用,不需要单独为 User 类型做适配。

核心逻辑说明

  • ReturnType<T['fetch']> 等价于 C++ 的 decltype(std::declval<T>().fetch()),作用是提取 T 类型上 fetch 方法的返回值类型
  • Awaited<> 用来把 Promise<Discord.User> 里的实际类型 Discord.User 提取出来

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:15:06