Narrowing

typeof guards

A typeof check splits a union into one branch per possible type. Inside the string branch, the value behaves as a string with full method support. The compiler tracks the guard without any extra annotation.

function shout(value: string | number): string { if (typeof value === "string") { return value.toUpperCase(); } return value.toFixed(0); } console.log(shout("hi")); console.log(shout(3.7));

HI

4

Truthiness guards

An if around the value itself removes null, undefined, zero, and empty string in one move. The surviving branch holds only real content. Guard optional values this way before touching their properties.

function hello(name?: string): string { if (name) { return "Hello, " + name; } return "Hello, guest"; } console.log(hello("Ada")); console.log(hello());

Hello, Ada

Hello, guest

The in operator

The in operator tests whether an object carries a given property name. Each branch of the check exposes a different union member. Use it when siblings share no common tag field.

type Cat = { meow: boolean }; type Dog = { bark: boolean }; function speak(pet: Cat | Dog): string { if ("meow" in pet) { return "meow"; } return "woof"; } console.log(speak({ meow: true })); console.log(speak({ bark: true }));

meow

woof

instanceof

The instanceof operator checks which class built the object. The matched branch unlocks that class and its methods. Prefer it for real class hierarchies, not for plain object shapes.

class Cup { drink(): string { return "sip"; } } function use(item: Cup | string): string { if (item instanceof Cup) { return item.drink(); } return item; } console.log(use(new Cup())); console.log(use("tea"));

sip

tea

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a typeof value === "string" check do to a string | number?

    Answer

    It narrows the value to the string branch

    Inside the branch the compiler knows the type, so string methods are allowed there.

  2. Which values does an if (value) guard remove from the branch?

    Answer

    The falsy ones: null, undefined, zero and the empty string

    The branch runs only for values that are truthy, which leaves real content.

  3. What does the in operator check?

    Answer

    Whether an object carries a given property name

    Each branch of the check exposes the union member that has the property.

  4. What does item instanceof Cup check?

    Answer

    Which class built the object

    The operator looks at the prototype chain, so it fits real classes rather than plain shapes.

  5. What does this program print? function shout(value: string | number): string { if (typeof value === "string") { return value.toUpperCase(); } return value.toFixed(0); } console.log(shout("hi"));

    Answer

    HI

    The string takes the first branch, which returns the upper case text.

  6. What does this program print? function shout(value: string | number): string { if (typeof value === "string") { return value.toUpperCase(); } return value.toFixed(0); } console.log(shout(3.7));

    Answer

    4

    The number branch rounds to a whole number with no decimals, which prints as 4.

  7. What does this program print? function hello(name?: string): string { if (name) { return "Hello, " + name; } return "Hello, guest"; } console.log(hello());

    Answer

    Hello, guest

    The missing argument is undefined, the guard fails and the fallback text is returned.

  8. What does this program print? type Cat = { meow: boolean }; type Dog = { bark: boolean }; function speak(pet: Cat | Dog): string { if ("meow" in pet) { return "meow"; } return "woof"; } console.log(speak({ bark: true }));

    Answer

    woof

    The object carries bark, so the in check fails and the fallback is returned.

  9. What does the compiler say about this program? type Cat = { meow: boolean }; type Dog = { bark: boolean }; function speak(pet: Cat | Dog): string { return pet.meow ? "meow" : "woof"; } console.log(speak({ meow: true }));

    Answer

    error TS2339: Property 'meow' does not exist on type 'Cat | Dog'.

    The union may hold a Dog, so a property of one member is not available before a check.

  10. What does the compiler say about this program? class Cup { drink(): string { return "sip"; } } function use(item: Cup | string): string { return item.drink(); } console.log(use(new Cup()));

    Answer

    error TS2339: Property 'drink' does not exist on type 'string | Cup'.

    The value may still be a string, so the method of Cup needs a guard first.

Article author: Arthur Isaev