What's the expected behavior when using this
inside a function in an object literal?
For example, let's say I have a type foo
that only has a function named bar
and no other property on it. But in the fooObj.bar
method, I'm able to access this.baz
(where baz
is not a property on type foo
) I see no error. Shouldn't typescript error out, as fooObj
does not have baz
on it?
type foo = {
bar(): void;
}
var fooObj: foo = {
bar: () => {
// TS does not error out when I access this.baz
console.log(this.baz);
}
}
Setting the "noImplicitThis": true
compiler option is how you would enable this functionality now. This pull request enabled typed this
in object literals. Aleksey L originally suggested this compiler option in a comment on the question, but at the time it didn't function that way.