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();
}- ✓Correct answer: It narrows the union to the members that have a
swimproperty - 2The
inoperator doesn't affect types - 3It checks that
ais an array containing the string'swim'
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.