JavaScript allows functions to work flexibly when the arguments passed are of different types and/or at different positions:
- The useState Hook lets you pass an initial value or a function for lazy initialization, or you can skip it altogether and pass nothing to it.
- The query API from node-postgres accepts an optional callback function and returns a promise when the callback function isn’t provided.
- The write function of the file system API in Node.js defines the first argument to be either a buffer of data or a string that we write to a file.
- The extend API from the package node-extend enables deep copying by allowing you to pass an optional boolean flag as the first argument to the function call.
It’s been a running theme in my TypeScript career: I have to create and type functions like these, and I’ve definitely struggled. But, I’ve found a few solutions that have worked for me. In this post, I’ll walk you through some techniques I use to type polymorphic functions more easily.