Tsallaka zuwa abun ciki
Justice Tech School

Type Narrowing

typeof, instanceof, in and equality checks narrow a union inside a branch.

Example
function f(x: string | string[]) {
  if (Array.isArray(x)) return x.join(",");
  return x.toUpperCase();
}
console.log(f(["a", "b"]), f("c"));

Result

a,b C

Exercise

Check a type.

if ( x === "string")

Quiz Test

What does narrowing do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.