【问题标题】:'thisArg' context not correctly recognized in bound function with TypeScript在使用 TypeScript 的绑定函数中无法正确识别“thisArg”上下文
【发布时间】:2020-07-17 12:52:26
【问题描述】:

使用下面的代码,TypeScript 将无法识别 thisArg 的上下文(应该是 a 并且应该有 saySomething() 方法。还有其他方法可以为 TypeScript 提供 thisArg 的上下文吗?

代码:

class A {
    saySomething() {
        console.log('Hello!');
    }
}

class B {
    constructor(a: A) {
        const boundSaySomething = this.saySomethingMyself.bind(a);
        boundSaySomething();
    }

    saySomethingMyself() {
        this.saySomething();
    }
}

const test = new B(new A());

控制台正确记录Hello,但类型检查显示

Property 'saySomething' does not exist on type 'B'.(2339)

【问题讨论】:

    标签: typescript this typechecking


    【解决方案1】:

    我认为这对 linter 来说太混乱了,我宁愿玩继承。 我只是建议您转换为 any ,因为转换为 "A" 类型不起作用:

    saySomethingMyself() {
        (<any>this).saySomething();
    }
    

    【讨论】:

    • 感谢您的反馈。你会怎么玩继承?为什么投射到A 不起作用(如果你知道的话)?
    • 我认为您只能将“this”上下文与类似 baseClass 的相关内容进行转换,而 就像一个小丑来退出打字,不确定......所以如果你编辑 B要扩展 A,B 将具有可通过继承访问的 saySomething 方法,并且(可选)您可以将“this”转换为 A 类型而不是“any”
    【解决方案2】:

    This answer 解决了我的问题。

    基本上,我不得不

    通过添加它(及其类型)来更改任何函数中 this 的上下文 作为函数的第一个参数。

    就我而言,我必须将 saySomethingMyself 方法从 saySomethingMyself() 更改为 saySomethingMyself(this: A)

    完整的更新代码:

    class A {
        saySomething() {
            console.log('Hello!');
        }
    }
    
    class B {
        constructor(a: A) {
            const boundSaySomething = this.saySomethingMyself.bind(a);
            boundSaySomething();
        }
    
        saySomethingMyself(this: A) {
            (this).saySomething();
        }
    }
    
    const test = new B(new A());
    

    【讨论】:

      【解决方案3】:

      您需要为您的方法注解this 类型。

      saySomethingMyself(this: A) {
      

      完整解决方案:

      class A {
          saySomething() {
              console.log('Hello!');
          }
      }
      
      class B {
          constructor(a: A) {
              const boundSaySomething = this.saySomethingMyself.bind(a);
              boundSaySomething();
          }
      
          saySomethingMyself(this: A) {
              this.saySomething();
          }
      }
      
      const test = new B(new A());
      

      Playground

      【讨论】:

      • 是的,感谢您的反馈,这是我找到并发布的答案。
      • 只有一个问题:您是如何共享游乐场的?只需复制网址?
      • 是的,我点击了 Cmd + S(它会为你复制 URL)。
      猜你喜欢
      • 1970-01-01
      • 2014-11-04
      • 2022-06-17
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多