What is the output?
function twice(x: number | string) {
return typeof x === 'number' ? x * 2 : x.repeat(2);
}
console.log(twice(3), twice('ab'));
- 6 NaN
- 6 abab
- 33 abab
- 6 ab2
The typeof check narrows x: numbers are doubled, strings are repeated.
Play Problem Solving ▸