Skip to content

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

@mtreder

Description

@mtreder

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

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions