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.
Official answer available
Preview the opening of the answer, then unlock the full walkthrough.
To start, let's clarify what we mean by Type Narrowing. In TypeScript, variables can be declared with a broad type, such as string | number. Type Narrowing allows us to dynamically determine the specific type of such variables within a specific scope, based on conditional checks. This is particularly useful in conditional blocks, where the type of a variable can be inferred based on the conditions that are true.
For example, consider a variable data that can either be a number or a string. In a scenario where we want to perform an operation specific to the number type, we'd first need to ensure data is indeed a number. Here's how we can apply Type Narrowing using an if-else condition:...