Skip to content
TypeScript·Intermediate·Coding·1 min read

What is type narrowing?

Short interview answer

Narrowing is TypeScript refining a value from a broader static type to a more specific type based on control-flow evidence. typeof, equality checks, in, instanceof, discriminants, and user-defined type predicates can all contribute evidence.

Example

TypeScript
function format(x: string | number) {  if (typeof x === 'string') {    return x.trim();      // x is string here  }  return x.toFixed(2);    // x is number here}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Type narrowing

Related questions