在对象字面量的函数中使用 this
时预期的行为是什么?
例如,假设我有一个类型 foo
,它只有一个名为 bar
的函数,没有其他属性。但是在 fooObj.bar
方法中,我能够访问 this.baz
(其中 baz
不是 类型的属性foo
) 我没有看到错误。 typescript 不应该出错,因为 fooObj
上没有 baz
吗?
type foo = {
bar(): void;
}
var fooObj: foo = {
bar: () => {
// TS does not error out when I access this.baz
console.log(this.baz);
}
}
最佳答案
设置 "noImplicitThis": true
编译器选项是您现在启用此功能的方式。 This pull request在对象字面量中启用类型 this
。 Aleksey L 最初在对该问题的评论中建议了这个编译器选项,但当时它并没有那样工作。
关于javascript - typescript 对象文字 "this"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40268795/