Skip to content

Typeguard should use conditional types #23764

Closed
@mkulke

Description

@mkulke

TypeScript Version: 2.9.0-dev.20180428

Search Terms:

conditional types, type guards

Code

type Pred<T, U extends T> = (v: T) => v is U;
function someFn<T, U extends T>(pred: Pred<T, U>, val: T): void {
  if (pred(val)) {
    const u: U = val;
    console.log(u);
    return;
  }
  const notU: Exclude<T, U> = val; // Type 'T' is not assignable to type 'Exclude<T, U>'.
  console.log(notU);
}

Expected behavior:

The code should compile, the predicate type-guard sets val to U in the "true" branch, and to Exclude<T, U> in the "false" branch.

Actual behavior:

In the "false" branch val is inferred to be T:

Type 'T' is not assignable to type 'Exclude<T, U>'.

Playground Link: https://bit.ly/2HAtMpF

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions