Description
The lack of IntelliSense to this
in functions inside object literals was reported in #7801 and #8110. #8382 attempted to fix that but it was reverted via #8389 due to #8191.
Adding this: this
to functions in an interface, as mentioned in #9583, was a suggested way to workaround this issue. However, it is not convenient to define this: this
for each method of an interface. Also, even when the object implements an interface, it may contain additional properties that are used in the interface methods but not exposed via the interface. Finally, like microsoft/vscode#298, there may be no interface at all.
Although typing this
in functions inside object literals cannot be switched on by default, I think there should be a way to opt in. Could something be applied to an object literal to explicitly mark this
in all methods of that object be the type of the surrounding object?
In the following examples, @
is a symbol that
- When it is placed immediately before the open bracket of an object literal,
this
in all methods of that object is of the type of the surrounding object. - When it is located after
this:
in a method declaration inside an object literal,this
in that method is of the type of the surrounding object.
Example 1--this
being the surrounding object in all methods of an object literal:
let o = @{
prop: 12,
bar() {
this.prop = 3; // `this` is inferred
},
foo() {
this.bar(); // `this` is inferred
}
};
Example 2--this
being the surrounding object in a method of an object literal:
let o = {
prop: 12,
bar(this: @) {
this.prop = 3; // `this` is inferred
},
foo() {
this.bar(); // `this` is any here
}
};
Example 3--this
being the surrounding object in all methods of an object literal that implements other interfaces:
interface I {
bar(); //`this: this` not required
foo(); //`this: this` not required
}
let o1: I = @{
prop: 12,
bar() {
this.prop = 3; // `this` is inferred
},
foo(this: any) {
this.bar(); // `this` is any
}
} as I;
let o2: I = <I>@{
prop: 12,
bar() {
this.prop = 3; // `this` is inferred
},
foo(this: any) {
this.bar(); // `this` is any
}
};