Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type narrowing regression with switch + for in TypeScript 4.9 #51688

Closed
mtreder opened this issue Nov 29, 2022 · 2 comments · Fixed by #51703
Closed

Type narrowing regression with switch + for in TypeScript 4.9 #51688

mtreder opened this issue Nov 29, 2022 · 2 comments · Fixed by #51703
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@mtreder
Copy link

mtreder commented Nov 29, 2022

Bug Report

It is possible to generate a "Variable 'X' is used before being assigned." error on TypeScript 4.9 where it previously did not in TypeScript 4.8. This seems to be when we have combination of switch statements and for loop.

🔎 Search Terms

switch
for
type check

🕗 Version & Regression Information

  • This changed between versions 4.8.4 and 4.9.3
  • This continues to error with nightly.

⏯ Playground Link

TypeScript 4.8.4 Playground Example

TypeScript 4.9.3 Playground Example

Nightly Playground Example

💻 Code

function functionA(): "A" | "B" {
	return "A";
}

function functionB(key: string): string {
	return key;
}

export function functionC(): void {
	let unionVal = functionA();
	switch (unionVal) {
		case "A": {
			break;
		}
		default: {
			return;
		}
	}

	for (let line = 1; line <= 10; line++) {
		let key: string;
		switch (unionVal) {
			case "A": {
				key = "AA";
				break;
			}
		}
		functionB(key);
	}
}

🙁 Actual behavior

Variable 'key' is used before being assigned.

🙂 Expected behavior

No error

@jcalz
Copy link
Contributor

jcalz commented Nov 30, 2022

bisected to #51095

@ahejlsberg ahejlsberg self-assigned this Nov 30, 2022
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Nov 30, 2022
@ahejlsberg ahejlsberg added this to the TypeScript 5.0.0 milestone Nov 30, 2022
@ahejlsberg
Copy link
Member

Simpler repro:

declare function functionB(key: string): string;

function functionC(): void {
	let unionVal: "A" | "B" = "A";
	while (true) {
		let key: string;
		switch (unionVal) {
			case "A": {
				key = "AA";
				break;
			}
		}
		functionB(key);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants