Skip to content

Logical successive type guards #37258

Closed
Closed
@toddriley

Description

@toddriley

TypeScript Version: 3.9.0-dev.20200306

Search Terms:
successive type guards, conditional type guards, type guards

Code

function isNull(a: string | null): a is null {
  return a == null;
}

function doStuff(a: string | null, b: string | null) {
  if (a == null && b == null) {
    return;
  }

  if (a == null && b != null) {
    return;
  }

  if (a != null && b == null) {
    return;
  }

  a; // logically must be `string`, but inferred as `string | null`
  b; // logically must be `string`, but inferred as `string | null`
  a.length; // Object is possibly 'null'
}

Expected behavior:
a and b cannot logically be null, therefore it should be inferred that these are strings.

Actual behavior:
It is inferred that these variables are possibly null.

Playground Link:
https://www.typescriptlang.org/play/?ts=3.9.0-dev.20200305&ssl=1&ssc=1&pln=21&pc=2#code/GYVwdgxgLglg9mABDAzgORAG0wCgIYBciKUATjGAOaIA+iYWmAlEXsivY4gN4BQiiUgFMoIUkjYBeSZ2wBuXgF9evUJFgJEAEzgBlUcGD4iJclVqzMAGkQAjE2QrU6DbEx79kwRPkTTLiABkgXZ+Mq7MHgICwqLiCgLKnjDevv4RQSG2iACE4YzufNGCImJgCYhJAik+bHkBwaHpBVHRsWUVVYh4cogA9H2ImHCUMBB42ACeiAC2ICR2QogABqZOyza2IFDIYMBCpMJa3RyrjuYujMuetr0DQyNjE5jTcwu2S2dmlBt227v7Q5CY54U5rC6Wa4CPAAOkwQioUAAFndBgB5WwAKyE0HYiAADnAUCgYLYXogAOQRClKIA

Related Issues:
#9016

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions