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

如何在TypeScript中为绑定函数定义this的类型

如何在TypeScript中指定回调函数的this类型为MyClass

要让TypeScript知晓fn函数内部的this类型为MyClass,可以通过在函数参数列表中显式声明this类型参数实现——这是TypeScript专门提供的类型标注语法,该this参数不会被编译为实际的JavaScript代码,仅用于类型检查和智能提示。

修改后的代码如下:

class MyClass {
    constructor() {}

    func(fn: (this: MyClass) => any) {
        fn.bind(this)()
    }
}

这样修改后,当你在fn内部使用this时,TypeScript会自动将其类型推断为MyClass,同时也会校验调用fn时的this上下文是否符合要求。比如调用场景:

const myInstance = new MyClass();
myInstance.func(function() {
    // 此处this的类型会被TypeScript识别为MyClass,拥有类的所有属性和方法提示
    console.log(this);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:45:34