How Does typeof Narrow Types in TypeScript?

Learn How Does typeof Narrow Types in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

How Does typeof Narrow Types in TypeScript? is part of the TypeScript curriculum. It helps you express intent clearly while TypeScript checks code before emitting JavaScript.

Why this concept matters

Use this topic to make assumptions explicit at development time, improve editor feedback, and make refactoring safer. Type information is normally erased from emitted JavaScript, so validate untrusted runtime data at application boundaries.

Start with a small example

type Result = { ok: true; value: string } | { ok: false; message: string };

function describe(result: Result): string {
  return result.ok ? result.value : result.message;
}

Prefer precise types over any, narrow unions before using specialized members, and use runtime checks for data from users, networks, or storage.

Code Examples

A narrow, explicit contract

typescript
type Result = { ok: true; value: string } | { ok: false; message: string };

function describe(result: Result): string {
  return result.ok ? result.value : result.message;
}
    

Pro Tip

Let inference do routine work, then add explicit types at an API boundary or where they prevent an incorrect assumption.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.