Skip to content

TypeScript 2.9 incorrect generator this value in ES5 #24564

@zenorbi

Description

@zenorbi

TypeScript Version: Version 3.0.0-dev.20180601 and also Version 2.9.1

Search Terms: ES5 generator this value

Code

class Test {
	async getChildren() {
		const randomItems = await this.someRandomMethod();

		const processedItems = randomItems.map((item) => {
			return this.doSomeProcessing(item); // <-- this will have incorrect _this value!
		});

		return ([] as string[]).concat(...processedItems); // <-- if I don't cast here, the above _this is good
	}

	private doSomeProcessing(stuff: string) {
		return stuff;
	}

	private async someRandomMethod() {
		return ["a", "b", "c"];
	}
}

Expected behavior:
this.doSomeProcessing(item) points to a correct this value

Actual behavior:
The emitted code has var _this = this but in the wrong scope

Playground Link:
http://www.typescriptlang.org/play/index.html#src=class%20Test%20%7B%0D%0A%09async%20getChildren()%20%7B%0D%0A%09%09const%20randomItems%20%3D%20await%20this.someRandomMethod()%3B%0D%0A%0D%0A%09%09const%20processedItems%20%3D%20randomItems.map((item)%20%3D%3E%20%7B%0D%0A%09%09%09return%20this.doSomeProcessing(item)%3B%20%2F%2F%20%3C--%20this%20will%20have%20incorrect%20_this%20value!%0D%0A%09%09%7D)%3B%0D%0A%0D%0A%20%20%20%20%20%20%20%20return%20(%5B%5D%20as%20string%5B%5D).concat(...processedItems)%3B%20%2F%2F%20%3C--%20if%20I%20don't%20cast%20here%2C%20the%20above%20_this%20is%20good%0D%0A%20%20%20%20%20%20%20%20%2F%2Freturn%20(%5B%5D).concat(...processedItems)%3B%20%2F%2F%20%3C--%20no%20casting%20version%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20private%20doSomeProcessing(stuff%3A%20string)%20%7B%0D%0A%09%09return%20stuff%3B%0D%0A%09%7D%0D%0A%0D%0A%09private%20async%20someRandomMethod()%20%7B%0D%0A%09%09return%20%5B%22a%22%2C%20%22b%22%2C%20%22c%22%5D%3B%0D%0A%09%7D%0D%0A%7D%0D%0A%0D%0Aasync%20function%20testCalling()%20%7B%0D%0A%20%20%20%20try%20%7B%0D%0A%20%20%20%20%20%20%20%20const%20tester%20%3D%20new%20Test()%3B%0D%0A%20%20%20%20%20%20%20%20const%20children%20%3D%20await%20tester.getChildren()%3B%0D%0A%20%20%20%20%20%20%20%20alert(children)%3B%20%2F%2F%20Expecting%3A%20a%2C%20b%2C%20c%0D%0A%20%20%20%20%7D%20catch%20(err)%20%7B%0D%0A%20%20%20%20%20%20%20%20alert(err.stack)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0AtestCalling()%3B%0D%0A

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions