Skip to content

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

Closed
@nkeynes

Description

@nkeynes

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions