Skip to content
Advertisement

Using union type as function parameter

I have a type defined like so:

JavaScript

where FieldValue is a union of types:

JavaScript

I have a variable object where I then declare the functions set by the above types:

JavaScript

This produces an error where the values in the object are not of type FieldToAction, I kind of understand why since I am now constraining the parameter to be a string or string[].

My question is: Is there a way of still using the union of types’ type and constraining the value in the parameter?

Thank you

Advertisement

Answer

Instead of using union | you should use intersection &. Intersection of functions produces a function overloading.

JavaScript

For instance, imagine you have this:

JavaScript

fn expects never because TS is trying to find most common type, which will conform each function in a union. To find such common type, TS intersects function arguments. It means that fn expects string & number, which in turn evaluates to never. See this legendary answer.

Let’s try this:

JavaScript

Now, fn expects "a" because it is safe to provide this to both functions. string & "a" === "a".

This is why you almost never want to end up with union of functions.

Advertisement