How Do instanceof and in 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.