TypeScript · Senior · Question 62 of 75

What does a this is predicate do in a class method?

class Node {
  isLeaf(): this is Leaf { return this.children.length === 0; }
}

Explanation

Calling if (node.isLeaf()) narrows node inside the branch, like a regular type guard.

Further reading

Problem with a question

TypeScript · Senior · question 62

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz