What is Type Narrowing in TypeScript, and how can it be applied in conditional blocks?
Instruction: Explain the concept of Type Narrowing with examples showing its application in if-else conditions.
Context: Aims to test the candidate's proficiency in TypeScript's type system, focusing on Type Narrowing and its significance in conditional logic to ensure type safety.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Narrowing uses control-flow information to refine a value's static type within a branch. The runtime check is ordinary JavaScript; TypeScript reasons about what that check establishes.
function formatValue(value: number | string | null): string { if (value === null) { return "missing"; } else if (typeof value === "number") { return value.toFixed(2); } else { return...