Narrowing return type of function is a little bit strange in TypeScript. So I share use cases below from bad to good 🙂
Use Cases
Usage 1 – Bad usage
Notice that even I call foo(0)
in line 8, when I hover mouse on foo
in line 8, popup shows val parameter type as string | number
union type. But it should show as number. So it is not narrowing parameter and return type of function.
Usage 2 – Bad usage
This usage narrows parameter and return type of function as literal type. But we need to narrow to type of parameter not value of parameter as literal type. Popup shows generic parameter type as 0
, that's why, parameter and return type becomes 0
.
Usage 3 – Good usage (function overloads)
Usage 4 – Good usage (function overloads with generic type)
Notice that generic type is used in line 43.