TypeScript · Junior · Question 29 of 75
How do you narrow string | number to string inside a condition?
- ✓Correct answer:
if (typeof value === 'string') { ... } - 2
if (value is string) { ... } - 3
if (value instanceof String) { ... }
Explanation
TypeScript analyzes control flow: after a typeof check, the type inside the branch is narrowed to string, and in else to number. instanceof String checks for a wrapper object, not a primitive. The x is T syntax is used in the signature of type guard functions.