Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type polymorphic functions in TypeScript - zhenghao #8384

Open
guevara opened this issue Mar 26, 2022 · 0 comments
Open

Type polymorphic functions in TypeScript - zhenghao #8384

guevara opened this issue Mar 26, 2022 · 0 comments

Comments

@guevara
Copy link
Owner

guevara commented Mar 26, 2022

Type polymorphic functions in TypeScript - zhenghao



https://ift.tt/PcZpuXQ






Type polymorphic functions in TypeScript

#typescript

Published on 19 February, 2022Last updated on 14 March, 2022

you might or might not need to use function overload

Admittedly, the title might be bit broad. Polymorphism is a theoretical concept that’s deeply rooted in programming language theory, and it has many varieties. I am by no means an expert in programming language theory. So, I won’t use the term “polymorphic functions” in this blog post in a strict, academic sense. 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. ad-hoc polymorphisms) and those that take a variable number of arguments (i.e. variadic functions).

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.

Union type#

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. For example:

The argument’s type could either be a string or boolean, so we use a union type to model this. Then, we use type guards inside the function body to narrow it down to its single type, i.e., string or boolean.

Now, let’s say the return value’s type depends on which specific union member the argument’s type is. How should we then go about typing it? We can represent the types of the arguments using generic types. Then, we pass them to conditional types to retrieve the right type of return value.

Let’s consider a function that generates a random integer from 0-9 when called with the string int. Or, it generates a random English letter from a - z when called with the string char.

Here’s how I would write it in JavaScript:

To properly type this in TypeScript, follow these steps:

  1. The argument str has the string union type "int" | "char" , and to make the return value’s type depend on the argument type, we must use a generic type T to represent it.
    1. function getRandom<T extends'char' | 'int'>(str: T)
  2. Pass T to a generic conditional type GetReturnType to get the respective type for the return value.
    1. type GetReturnType<T> = T extends 'char' ? string : T extends 'int' ? number : never

Putting these together we have:

You might be wondering about the type assertion after each return statement. I’ll explain this later.

Now, let’s say we must expand our getRandom function to also support random boolean generation.

First, we must add another union member bool to our string union type for the argument. That’s easy. But as a result, the conditional expressions inside GetReturnType quickly gets crowded:

As you can tell, this doesn’t scale well if we keep adding more types for the function to support. Luckily, we can create a record type for indexed access with type parameter T, which we defined for our argument’s type.

Think about the DOM API documnet.querySelector—it accepts an html element tag name and returns the respective html element. It is typed in TypeScript’s source code in the exact same way.

You might’ve have noticed that I added a type assertion as ReturnTypeByInputType[T] for every return statement. This is because after TypeScript 3.5, to give a return value an indexed access type (such as ReturnTypeByInputType[T]), the return type must be checked against the intersection of all possibilities of the properties (types) selected by that index. In the above example, every return value must be asserted as either ReturnTypeByInputType[T], or an explicit intersection type of every type in ReturnTypeByInputType , which is number & string & boolean. Note that the resultant type of the intersection is never. Therefore type assertion with as never works too

This is to improve the soundness of the type system. See this PR if you are interested in learning more about it.

Type assertions are inherently unsafe. Later on, I’ll show you how to get rid of them using function overload. But unfortunately, function overload is just as unsafe as type assertion. For now though, just consider this as a technical limitation of TypeScript.

Optional parameters#

What about functions that take a variable number of arguments? They’re extremely common, and in JavaScript you don’t really need to do anything other than just define parameters as you normally would and check them against undefined inside the function body.

In TypeScript—you probably know this already—we can model it using optional parameters marked with ?:

Consequently, inside the function body, b is of the union type boolean | undefined

It’s also common for such functions to return different types of values if optional parameters are actually provided or not.

Let’s say we have a function search that fetches search results asynchronously. It accepts an optional callback function as the arguments. If the callback function is supplied, it passes the search results to it. Otherwise, it returns a promise that resolves to the search results. Here’s how you might write the function in JavaScript:

In TypeScript, we can follow these steps to type the function:

  1. First, we must mark the argument cb as an optional parameter with ?
  2. Then, we represent the argument cb's type with a generic type T
  3. Finally, we use extends to conditionally return the right type T extends Callback ? void : Promise<Result[]>

You might noticed that I added undefined as a type parameter default for T, i.e. function search<T extends Callback | undefined = undefined>.

The reason is that with the undefined default, the compiler can properly infer the type T when cb is not provided.

As you might’ve noticed, there are some common themes:

  1. We use extends with conditional expressions quite a lot to determine the right return’s type. And the syntax can get complicated pretty quickly.
  2. There are a lot of type assertions needed.

All of these added a lot of noise to our types. So, there might be a better alternative when it comes to type complex polymorphic functions...

Function overload#

It turns out that TypeScript supports function overload, and surprisingly, it might actually be the oldest part of TypeScript. You can trace it back to TypeScript 1.1. But unlike other features added during TypeScript’s early development—enums and namespaces come to mind, which tend to get overused (especially enums) and should be replaced by other features—from my observations, function overload is actually underused and still remains useful when needed.

I think part of the reason why function overload is so underused, is because the idea of function overload just feels unnatural to many JavaScript developers. In JavaScript, we don’t have function overload—JavaScript only allows one function with a specific name within a specific scope.

However, as a dynamically typed language, JavaScript performs type checks during runtime. This means arguments are as dynamic as we need them to be and allows us to achieve the same effect as function overload—namely, having different function implementations depending on the types and number of arguments that are invoked.

Depending on your background, TypeScript's function overload might feel a little weird to you since it is resolved at runtime by the implementer (the TypeScript programmer) by manually examining the arguments’ types.

TypeScript could’ve implemented the traditional compile-time function overload available from statically-typed languages like C++, C# and Java etc. In fact, multiple proposals, like this one, have asked for such a “proper” function overload feature, but they all ended up only being close as they all violate multiple TypeScript design goals.

A simple example of function overload#

Let’s consider a function that accepts either a number or a string, and that converts the input to the opposite type and returns it. That means, given a number, it returns the corresponding string; given a string, it returns the corresponding number. Here’s how you can write it in JavaScript:

This example is inspired by this tweet from @TkDodo

And here’s how you can type this function using generics and conditional types:

Now let’s try function overload to type this. Follow these steps:

  1. Write 2 separate function signatures for each version of the overloaded function
  1. Write the overloaded function implementation.
    1. Use a union type to encompass types of each of the overloads.
    2. Within the function body, we check the types of the arguments and manually dispatch the execution to a proper code path:

With function overload, you remove:

  1. Generics and the conditional types.
  2. Type assertions.

And you gain benefits like:

  1. Readability, since you can clearly distinguish the possible variant of the overloaded function. The types of arguments and return values are separately and explicitly written out.
  2. IDE support for overloaded functions is better.

A more complex example of function overload#

Rewind to our initial search function. Following the same steps, you can re-write it using function overload:

Again, no convoluted conditional types and generic types, and no annoying type assertions.

One last example of function overload in React#

React's useState hook is also overloaded to make it easier to use.

If you have an initial value or a function that returns a value then the state is going to be of the type of that value:

You can also skip passing an initial value to it, and instead specify a type. Then the state ends up being of the union type:

If you don't even specify a type, you will get a undefined state

This is also done via function overload.

Check out the source code if you are interested.

Overloaded functions are just as unsafe (even without type assertions)#

Type assertions are often considered to be code smell, and getting rid of them by leveraging function overload might seem like a big win. However, function overload is just as unsafe as type assertions.

Let’s go back to our switchIt_overloaded example and intentionally mess up its implementation to return the wrong types:

The TypeScript compiler only checks the function body’s code against the (overloaded) function signature but it cannot tell which if else branch is supposed to handle which individual overload. As a result, we can write code that contradicts the overloaded function signature and TypeScript can’t help us.

Function overload is just an intersection of function types#

Function overload can be thought of as a syntactic sugar for intersecting function types. Think about it—when we are overloading functions like:

Then we are saying that a value (i.e. that function) of this type (the function type/signature being overloaded) can be used both as a function of the first type/signature (input: string): number and as a function of the second type/signature (input: number): string. This effectively translates into an intersection of both function types/signatures:

And you can also write type F in the form of interface, since the interface definition automatically merges and is implicitly intersected by the compiler:

Flow is another popular JavaScript type system. But, it doesn’t (fully) support the function overload syntax in TypeScript. However, it does allow you to set overloading types for functions using intersection types, exactly like what we did above with switchIt_intersection.

Interestingly, the usage of intersection types for function overload (i.e. type F = ((input: string) => string) & ((input: number) => number)) is a common source of confusion to people: when the overloaded function signature is written, union types are used, as opposed to intersection types.

This is because parameter types are contravariant—you must reverse the type relationship (i.e. flip the ands and ors) inside the function body. 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.

My rule of thumb#

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. 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.

For example:

  1. 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).
  2. 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. Writing it using function overload would be extremely verbose. Functions with an excessive number of overloads can be confusing to people.

The bottom line is, whether you favour function overload or generic types with conditional types, we have to be very intentional about it and tread very carefully as neither of them is completely safe.







via zhenghao.io

March 26, 2022 at 03:49PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant