TypeScript · Middle · Question 26 of 75

How does TypeScript handle the in operator when narrowing?

type Fish = { swim(): void };
type Bird = { fly(): void };
function move(a: Fish | Bird) {
  if ('swim' in a) a.swim(); else a.fly();
}

Explanation

TS supports narrowing via typeof, instanceof, in, equality checks, truthiness and discriminants. In else, Bird remains. For network data, such checks are part of runtime validation.

Further reading

Problem with a question

TypeScript · Middle · question 26

Test yourself

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

Take this quiz