Skip to content

Generic type-guard with param narrows to 'never' on reachable code #12646

@aaronbeall

Description

@aaronbeall

TypeScript Version: 2.0.10

Code

interface Type { type: string; }
function isOfType<T extends Type>(target: Type, type: string): target is T {
  return target.type === type;
}

interface A extends Type { a: string; }
interface B extends Type { b: string; }
const TYPE_A = "a", TYPE_B = "b", TYPE_X = "x";

function test(target: Type) {
  if (isOfType<A>(target, TYPE_A)) {
    return target.a;
  }
  
  if (isOfType<A>(target, TYPE_A)) {
    return target.a; // No error?
  }
  
  if (isOfType(target, TYPE_X)) {
    return target;
  }
  
  if (isOfType<B>(target, TYPE_B)) {
    return target.b; // Error: TS2339:Property 'b' does not exist on type 'never'.
  }
}

Expected behavior:

Error on the second target.a because that code is not reachable.

No error on the last target.b because that code is reachable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions