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

添加TypeScript返回类型为何会破坏函数链式调用?

静态方法返回类型错误导致的TS编译问题解析

问题场景

类实现代码

export class KtorHttpAdapter {

    static application: IRatingUseCase

   public static from (app: IRatingUseCase): KtorHttpAdapter{
      KtorHttpAdapter.application = app;
      return this;
   }

   public static performSomeFunction (value: number): number {
     return KtorHttpAdapter.application.rateAndResult(value)
   }
}

调用代码

const application: IRatingUseCase = new RatingApplication(rater);

KtorHttpAdapter.from(application).performSomeFunction(5);

编译错误

Property 'performSomeFunction' does not exist on type 'KtorHttpAdapter'. Did you mean to access the static member 'KtorHttpAdapter.performSomeFunction' instead?

问题根源

你搞错了静态方法返回值的类型:

  • from是静态方法,内部的this指向的是KtorHttpAdapter类本身(构造函数对象),而非类的实例。
  • 你给from声明的返回类型是KtorHttpAdapter,这在TS里代表类的实例,但实际上你返回的是类本身。
  • TS据此认为from的返回值是实例,而performSomeFunction是静态方法,实例上不存在这个成员,所以抛出错误。

当你移除返回类型时,TS会自动推导返回类型为typeof KtorHttpAdapter(即类的构造函数类型),此时调用静态方法完全符合类型规则,编译自然通过。

修复方案

修改from方法的返回类型为typeof KtorHttpAdapter,明确返回的是类本身:

public static from (app: IRatingUseCase): typeof KtorHttpAdapter {
  KtorHttpAdapter.application = app;
  return this;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:44:54