Skip to content

Control flow with type guards forget previously computed props #18962

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

Closed
timocov opened this issue Oct 5, 2017 · 1 comment
Closed

Control flow with type guards forget previously computed props #18962

timocov opened this issue Oct 5, 2017 · 1 comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@timocov
Copy link
Contributor

timocov commented Oct 5, 2017

TypeScript Version: 2.5.3 / nightly (2.6.0-dev.20171005)

Code

interface Base {
	value?: string;
}

interface A extends Base {
	type: 'A';
	a: number;
}

interface B extends Base {
	type: 'B';
	b: string;
}

type Common = A | B;

declare var a: Common;

if (a.value !== undefined && a.type === 'A') {
	const str: string = a.value; // Error
}

if (a.type === 'A' && a.value !== undefined) {
	const str: string = a.value; // Ok
}

Expected behavior:
No errors.

Actual behavior:

error TS2322: Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.
@mhegazy mhegazy added Suggestion An idea for TypeScript In Discussion Not yet reached consensus labels Oct 5, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Oct 5, 2017

The first check narrows type of a.value to string, but the second check then narrows the type of a to A. Need to think of possible solutions here. It is possible to address this by fixing issues like #18840.

@timocov timocov closed this as completed Oct 27, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants