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

Guard variable with conjunctions does not narrow the conjoined operands #41870

Closed
nkeynes opened this issue Dec 8, 2020 · 1 comment · Fixed by #44730
Closed

Guard variable with conjunctions does not narrow the conjoined operands #41870

nkeynes opened this issue Dec 8, 2020 · 1 comment · Fixed by #44730

Comments

@nkeynes
Copy link

nkeynes commented Dec 8, 2020

TypeScript Version: 4.1.2 (strict)

Search Terms: conjunction falsy narrowing

Code

function foo( k: string | undefined, i: string ) : string {
   const g = k && i;
   if( g ) {
       return k;
   }
   return "";
}

function bar( k: string | undefined, i: string ) : string {
   if( k && i ) {
       return k;
   }
   return "";
}

Expected behavior:
I would expect both of these to typecheck in strict - in both cases k is only returned if it is non-falsy.

Actual behavior:
foo() fails to typecheck with the following error:

test.ts:4:8 - error TS2322: Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.

however, bar() does pass typechecking.

Playground Link:

Related Issues:

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants