Typesafe Function Overloading in TypeScript
Common frustrations with no easy solution
When helping developers new to TypeScript, I encounter several common patterns of frustration. Two broad categories:
- Type 1: Users get frustrated that certain JavaScript patterns are hard to express safely in TypeScript. This typically involves runtime reflection, which I won't discuss today and is usually an issue for less experienced or stubborn users (sometimes legitimately!).
- Type 2: Users understand TypeScript features in isolation but get confused combining them in seemingly natural ways that don't work as expected. Often this is simply because the feature combination hasn't been implemented.
We'll focus on a type 2 problem: function overloading and conditional types in TypeScript. This is an area many find unsatisfactory and I've seen attempted countless times. The intersection of these features comes up often in the TypeScript Discord and at work. The goal is type safety, but the result is confusing compiler errors.