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

如何在对象字面量的包装函数中推断TypeScript的ThisType?

实现包装函数的ThisType类型校验

先看原有场景:使用ThisType可以让对象字面量中的函数通过this正确访问对象已定义的属性,未定义属性会触发类型错误:

function define<A>(options: A & ThisType<A>) {}

define({
  a() {},
  w1: function () {
    this.a(); // *类型校验通过*
    this.b(); // *类型错误:属性'b'不存在*
    return () => {
      this.a(); // *类型校验通过*
      this.b(); // *类型错误:属性'b'不存在*
    };
  }
});

现在需要让包装函数wrapper也实现同样的类型校验效果:

function wrapper(fn: () => any) { return fn; }

define({
  a() {},
  w2: wrapper(function () {
    this.a(); // 期望:*类型校验通过*
    this.b(); // 期望:*类型错误*
  }),
});

解决方案

修改wrapper为泛型函数,明确接受带this参数的函数类型,让TypeScript能通过ThisType的上下文自动推断this的类型:

function wrapper<T>(fn: (this: T) => any) {
  return fn;
}

这样修改后,在define的对象字面量中使用wrapper时,ThisType<A>会自动将包裹函数的this类型绑定为对象的类型A,从而实现和w1完全一致的类型校验效果:

define({
  a() {},
  w2: wrapper(function () {
    this.a(); // *类型校验通过*
    this.b(); // *类型错误:属性'b'不存在于类型'{ a(): void; w2: (this: { a(): void; w2: any; }) => any; }'*
  }),
});

原理是:ThisType<A>会为对象内的函数提供this的上下文类型,而泛型wrapper的T会被自动推断为A,从而让包裹函数的this类型严格匹配对象的属性结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:13:03