Programming Languages

TypeScript Narrowing: A Small Example beyond Using any

Huwell Consultancy editorial2 min read

A TypeScript value can have more than one possible type. Narrowing means using a check that lets TypeScript understand which possibility applies in a part of the code. This is useful when explaining frontend work in a Malta developer interview.

Start with two possible inputs

function label(value: string | number): string {
  if (typeof value === "number") {
    return value.toFixed(0);
  }
  return value.trim();
}

Inside the number branch, value is treated as a number. After that branch returns, the remaining case is a string. The check explains why each operation is valid; replacing the input with any would lose that useful check.

Do not forget null

The TypeScript Handbook explains an important JavaScript detail: typeof null is “object”. An object check alone therefore does not prove that a value is safe to use. Also be careful with truthiness checks when an empty string or zero is valid input.

Try a small exercise

Change the input type to string | number | null. Decide what the function should return for null before editing the code. Then add a separate null branch. Try 0, an empty string and a word with surrounding spaces. Write down the expected output for each one.

Explain the choice

In an interview, say which inputs are allowed and what each branch does. The example is deliberately small. It helps you demonstrate that you understand the reason for a type check rather than only how to silence a compiler warning.

Sources and further reading

Browse current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision