benwaffle
benwaffle

Reputation: 332

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()?

Upvotes: 2

Views: 58

Answers (1)

CRice
CRice

Reputation: 32176

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
}

Upvotes: 4

Related Questions