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

如何强制指定按名称引用的方法的返回类型?

限制方法返回类型的TypeScript函数实现

原代码存在两个核心问题:

  1. keyof T包含对象的所有属性键,无法保证对应的属性是可调用的函数,导致f()调用时报错
  2. 没有约束方法的返回类型必须匹配expected,无法在编译阶段拦截不符合要求的调用

解决方案:通过泛型约束筛选符合要求的方法名

首先定义一个工具类型,用来提取对象类型T中**无参数且返回值为expected**的方法名:

type MethodReturningExpected<T> = {
  [K in keyof T]: T[K] extends () => expected ? K : never
}[keyof T];

这个类型的逻辑是:遍历T的所有属性键K,判断该属性是否是返回expected类型的无参函数,符合条件则保留键名,否则标记为never,最后取所有有效键的联合类型。

接着修改handle函数,将method参数的类型约束为上述工具类型:

type expected = {
    a: string;
}

type MethodReturningExpected<T> = {
  [K in keyof T]: T[K] extends () => expected ? K : never
}[keyof T];

function handle<T>(method: MethodReturningExpected<T>, handler: T) {
    const f = handler[method];
    return f(); // 此时f被推断为() => expected类型,可正常调用
}

class Handler {
    foo() {
        return 'bar';
    }
    baz() {
        return { a : 'bar'}
    }
}

handle('foo', new Handler()); // 编译错误:"foo"不属于符合要求的方法名
handle('baz', new Handler()); // 正常编译,返回类型符合预期

扩展说明

如果目标方法需要接收参数,只需调整工具类型中的函数签名即可,比如方法需要接收一个number类型参数:

type MethodReturningExpected<T> = {
  [K in keyof T]: T[K] extends (arg: number) => expected ? K : never
}[keyof T];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:13:16