TypeScript Narrowing Function Return Type Part 1

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.

Usage 5 – Good usage (narrowing return type and casting any when return a value from function)

Usage 6 – Good usage (same as Usage 5 but return type is a type alias)

Usage 7 – Good usage (same as Usage 6 but return type is a generic type which extends type alias)

Leave a Reply

Your email address will not be published.