CodePark/ questions / Unions & narrowing
START PRACTICINGPRACTICE
Frontend question · TypeScript › Unions & narrowing

Does this compile under strict?

function count(items: string[] | null) {
  if (typeof items === "object") {
    return items.length;
  }
  return 0;
}
No: items is possibly null, because typeof null is also "object"

No, it does not compile: items is possibly null. In JavaScript, typeof null is "object". TypeScript models this, so the check narrows items to string[] | null, not to string[].

The option "Yes: the
typeof check narrows items to string[]" is the tempting wrong answer for this reason. Use if (items) or items !== null instead.