Skip to content

Commit 08ae022

Browse files
committed
Contextually type this in object literals in JS
Previously, `this` would only get a contextual type inside object literals with `--noImplicitThis` turned on in Typescript files.
1 parent de9a67f commit 08ae022

4 files changed

Lines changed: 65 additions & 1 deletion

File tree

src/compiler/checker.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12602,7 +12602,7 @@ namespace ts {
1260212602
}
1260312603
}
1260412604
}
12605-
if (noImplicitThis) {
12605+
if (noImplicitThis || isInJavaScriptFile(func)) {
1260612606
const containingLiteral = getContainingObjectLiteral(func);
1260712607
if (containingLiteral) {
1260812608
// We have an object literal method. Check if the containing object literal has a contextual type
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
=== tests/cases/conformance/types/thisType/context.js ===
2+
const obj = {
3+
>obj : Symbol(obj, Decl(context.js, 0, 5))
4+
5+
prop: 2,
6+
>prop : Symbol(prop, Decl(context.js, 0, 13))
7+
8+
method() {
9+
>method : Symbol(method, Decl(context.js, 1, 12))
10+
11+
this;
12+
>this : Symbol(obj, Decl(context.js, 0, 11))
13+
14+
this.prop;
15+
>this.prop : Symbol(prop, Decl(context.js, 0, 13))
16+
>this : Symbol(obj, Decl(context.js, 0, 11))
17+
>prop : Symbol(prop, Decl(context.js, 0, 13))
18+
19+
this.method;
20+
>this.method : Symbol(method, Decl(context.js, 1, 12))
21+
>this : Symbol(obj, Decl(context.js, 0, 11))
22+
>method : Symbol(method, Decl(context.js, 1, 12))
23+
}
24+
}
25+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
=== tests/cases/conformance/types/thisType/context.js ===
2+
const obj = {
3+
>obj : { [x: string]: any; prop: number; method(): void; }
4+
>{ prop: 2, method() { this; this.prop; this.method; }} : { [x: string]: any; prop: number; method(): void; }
5+
6+
prop: 2,
7+
>prop : number
8+
>2 : 2
9+
10+
method() {
11+
>method : () => void
12+
13+
this;
14+
>this : { [x: string]: any; prop: number; method(): void; }
15+
16+
this.prop;
17+
>this.prop : number
18+
>this : { [x: string]: any; prop: number; method(): void; }
19+
>prop : number
20+
21+
this.method;
22+
>this.method : () => void
23+
>this : { [x: string]: any; prop: number; method(): void; }
24+
>method : () => void
25+
}
26+
}
27+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// @allowJs: true
2+
// @checkJs: true
3+
// @noEmit: true
4+
// @Filename: context.js
5+
const obj = {
6+
prop: 2,
7+
method() {
8+
this;
9+
this.prop;
10+
this.method;
11+
}
12+
}

0 commit comments

Comments
 (0)