

The getRandom function is not suitable for function overload since generic types with conditional types or indexed types are already a great tool to map input types to output types.The search function above is a good candidate for function overload since the return value’s type changes depend on the number of arguments that gets passed to the function (the shapes of the function signatures are very different).I only reach for function overload when I realize the function signature’s shapes for all its variants are different enough to be defined separately and explicitly. When it comes to typing polymorphic functions in TypeScript, I normally default to using generic types (constrained to a union type) along with conditional types. For example, if the function has a type of string => X and number => X, then you have to handle an input that is a string or a number when working inside the function body. flip the ands and ors) inside the function body.

This is because parameter types are contravariant-you must reverse the type relationship (i.e. interface works as well type ReturnTypeByInputType = Union types are probably the first, and most obvious, tool you want to reach for when typing a function that accepts arguments of different types. In this post, I’ll walk you through some techniques I use to type polymorphic functions more easily.

But, I’ve found a few solutions that have worked for me. It’s been a running theme in my TypeScript career: I have to create and type functions like these, and I’ve definitely struggled. 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.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 query API from node-postgres accepts an optional callback function and returns a promise when the callback function isn’t provided.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.JavaScript allows functions to work flexibly when the arguments passed are of different types and/or at different positions: ad-hoc polymorphisms) and those that take a variable number of arguments (i.e. Rather, I will use it mainly to refer to functions in two ways: those that behave differently depending on their applied argument types (i.e. So, I won’t use the term “polymorphic functions” in this blog post in a strict, academic sense. I am by no means an expert in programming language theory. Polymorphism is a theoretical concept that’s deeply rooted in programming language theory, and it has many varieties. You might or might not need to use function overloadĪdmittedly, the title might be bit broad. Published on 19 February, 2022 Last updated on 14 March, 2022
