Search code examples
typescriptnarrowingtype-narrowing

Is there a way to achieve type narrowing by checking with a function?


class A {}
class B extends A {
  bb() { ... }
}

function isB(obj: A) {
  return obj instanceof B;
}

const x: A = new B(); // x has type A
if (isB(x)) {
  x.bb(); // can I get x to have type B?
}

I know that if I have x instanceof B in the condition it will work. But can I do it through isB()?


Solution

  • Typescript supports this with a special return type, X is A. You can read about this more in their section on user defined type guards.

    For your example, you might type it like this:

    class A {}
    class B extends A {
      bb() { ... }
    }
    
    function isB(obj: A): obj is B { // <-- note the return type here
      return obj instanceof B;
    }
    
    const x: A = new B(); // x has type A
    if (isB(x)) {
      x.bb(); // x is now narrowed to type B
    }