【问题标题】:What does 'this' context type void not assignable to type rule mean?'this' context type void not assignable to type rule 是什么意思?
【发布时间】:2020-08-27 13:50:05
【问题描述】:

我正在 Typescript 中运行一些测试,看看我想做的事情是否可行。我需要将函数内部的“this”类型设置为类;它有效,但是,我不断收到错误消息:“void”类型的“this”上下文不可分配给“Rule”类型的方法“this”。下面是代码。

TLDR 如何在独立函数中指定 this 的类型?

PS 也许有更好的方法可以做到这一点,所以我将解释我想要做什么:我想要做的是创建一个规则类,我在其中添加一个函数如果返回 true 或 false,则返回注释和状态。我不希望函数有一堆参数。我希望该类能够与其他类交互并访问其他数据,但为了测试目的而独立。

export class Rule {
    constructor(rule) {
      this.Fx = rule
}
    Fx;
    passNote;
    failNote;
    guest;
    apiData;
    runRule(dev) {
     this.Fx(dev)
    }
}

function apple(this: Rule, dev) {}

const test = new Rule((dev) => dev.pass)
const dev = // large object I am testing with the rule
test.runRule(dev)
 // The 'this' context of type 'void' is not assignable to method's 'this' of type 'Rule'

在编写我在构造函数中使用的函数时,我想要的只是“this”的智能。

【问题讨论】:

  • "。我不希望函数有一堆参数"真的吗?传递一个对象怎么样?

标签: javascript typescript


【解决方案1】:

你可以.call苹果:

 apple.call(new Rule, 'poop');

【讨论】:

    【解决方案2】:

    我不完全确定你想用apple 函数完成什么,但这与this 绑定的工作方式有关。我建议阅读更多关于它的内容here,但是当您正常调用函数时(就像您在代码中使用的那样),this 上下文在不处于严格模式时指的是全局范围,undefined 在处于严格模式时指的是全局范围严格模式。您的 TypeScript 代码可能在严格模式下编译为 JavaScript,因此错误试图告诉您此 undefined 值不是 Rule 类型。如果想让this引用类对象的一个​​实例,可以把它赋值给对象,通过对象绑定来调用,而不是直接调用函数:

    function apple(this: Rule, dev) {}
    export class Rule {
        constructor() {}
        Fx;
        passNote;
        failNote;
        guest;
        apiData;
        apple = apple;
    };
    
    const rule = new Rule();
    rule.apple('test'); // now the this keyword will refer to the Rule object you instantiated
    

    或者,您可以将对象作为自己的参数传递给apple 函数,而不是尝试使用this。由于当您不完全了解它的工作原理时,使用 this 关键字可能会让人感到困惑,我建议您使用这种方法:

    const rule = new Rule();
    function apple(rule: Rule, dev) {}
    apple(rule, 'test');
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 2022-11-20
      • 2023-02-15
      • 2022-01-26
      • 2022-12-27
      • 2022-12-27
      • 1970-01-01
      • 2015-08-20
      相关资源
      最近更新 更多