typescript
How I create complex TypeScript types
Who's this for?
This article is tailored for developers who’ve gotten their hands dirty with TypeScript and its type system. If you’re comfortable with generics and have wrestled with some complex types before, you’re in the right place.
I’m often asked how I learned to create complex TypeScript types, so in this article I’d like to share my thought process with a real-world example.
With the experience I’ve accumulated over the years, I know what TypeScript can and can’t do. I don’t go through all the steps anymore. I often skip naive implementations as I know they won’t work beforehand, and I don’t need to think in pseudo-code first. The TypeScript type system code has become just like any other programming language for me.
This was the process I went through when I first started, so I hope it will be useful to someone out there. Also, please keep in mind that what works for me might not work for you.
The type I’m going to use as the example is something I had to work on at my job, a pipe function. You might have used it already, maybe even implemented it, so let’s see how to type it.
What is a pipe, actually?
The concept of pipes has been around for quite some time, probably since 1964.
There are mainly two kinds of pipes: Unix pipes and pipes used in programming languages. They are similar in what they do, but differ in how they achieve it; in this article we’ll obviously focus on the latter.
My mental model of a pipe is this: some initial data passed through a series of functions where the output of one is the input of the next one. If you’re familiar with math, that would be an input provided to the result of a function composition.
To visualize it, something akin to this:
The Basic Implementation
Many languages have a pipe operator built in, but JavaScript, and thus TypeScript, lack one (for now at least, there’s a pending proposal), so we have to implement our own functionality.
I start by writing the JS code without types.
In JS, a terse implementation would look something like this:
const pipe = (data, ...fns) =>
functions.reduce((output, fn) => fn(output), data);I add primitive types to the JS code to get an overview of the data flow.
Now that we have the runtime code, let’s focus on the types by adding the primitive ones. This will give us a clearer picture of what we’re dealing with.
declare const pipe: (data: any, ...fns: readonly Function[]) => any; We can now observe that data can be any value, while fns is an array of functions, and the return can be any value.
Before going crazy with the types, I write down all the constraints I’m aware of at this time.
So far we know that:
-
typeof datahas to be assignable to the argument offns.at(0). -
pipe’s return type should be the same asfns.at(-1)’s.
With these constraints in mind, I try creating a simple version of the type.
With the help of generic type parameters, we can try writing a simplified version that accepts only one function:
declare const pipe: <D0, D1>(data: D0, fn1: (arg: D0) => D1) => D1;Does this work? It should… Let’s check if our constraints hold true:
-
typeof data(D0) has to be assignable to the argument offns.at(0). -
pipe’s return type (D1) should be the same asfns.at(-1)’s.
Our requirements are met, so everything should work fine. Let’s try with a helper function:
declare const const formatNumber: (input: number) => stringformatNumber: (input: numberinput: number) => string;
const const probe: stringprobe = const pipe: <0, string>(data: 0, fn1: (arg: 0) => string) => stringpipe(0, const formatNumber: (input: number) => stringformatNumber);
This seems to be working fine, but what happens when data is not a number?
const const probe: stringprobe = const pipe: <number, string>(data: number, fn1: (arg: number) => string) => stringpipe("0", const formatNumber: (input: number) => stringformatNumber);The error seems to be kinda in the wrong place? I know that’s debatable, but for me the error should be on the function, and not on the initial value.
This happens because D0 is inferred as fn1’s parameter, so data is forced to be number. Can we somehow fix that? Yes, in TypeScript 5.4 we’ve got a utility for this called NoInfer. This built-in type tells the type system to infer the generic type parameter from some other place.
declare const pipe: <D0, D1>(
data: D0,
fn1: (arg: NoInfer<D0>) => D1,
) => NoInfer<D1>; Now we are sure that data’s type will be inferred from the parameter itself. If we try again we can see that the error moved to the function, telling us that a function that takes a number as an input is not assignable to one that takes a string (a.k.a. the function we were expected to provide).
const const probe: stringprobe = const pipe: <string, string>(data: string, fn1: (arg: string) => string) => stringpipe("0", formatNumber); Cool! Our pipe works correctly now.
At this point I try making the type more generic.
So far this function is pointless, because we can only call it with one function. It would’ve been simpler to just call formatNumber("0").
Sadly, to the best of my knowledge, as of TypeScript 5.6, there’s no way to tell the type system that “all these functions should have a return type that’s assignable to the next one”. At least not from a type-theory point of view… Our best bet is to overload the function and keep adding more generic type parameters:
declare const pipe: {
<D0, D1>(data: D0, fn1: (arg: NoInfer<D0>) => D1): NoInfer<D1>;
<D0, D1, D2>(
data: D0,
fn1: (arg: NoInfer<D0>) => D1,
fn2: (arg: NoInfer<D1>) => D2,
): NoInfer<D2>;
// and so on…
};The Programmatic Implementation
If the previous step fails, I try a programmatic implementation of the type.
The type system within TypeScript is a Turing Complete, pure functional programming language, with some limitations – usually the number of recursive calls it allows. This means that if you find a way to express your type as a program, you’re good to go! When I learned this, my perspective shifted, and everything became clearer. I hope it’s the same for you.
I check if I can express the type I need as a program. Usually in an imperative programming paradigm, then I convert it in a functional programming paradigm.
Considering that we don’t have many constraints, and that they’re not complex, I think we can express the type as a program. Let’s start by writing a function that returns the correct chain of functions in a JS-like pseudo-code that can mix types and values.
const expectedChain = (fns, data) => {
const chain = [];
let lastData = @typeOf(data);
for (const [fn, index] of fns) {
// we declare the function we expect to see
const expectedFunction: (parameter: lastData) => any;
if (@extends(expectedFunction, @typeOf(fn))) {
// if the type of the expected function extends the one
// we're currently testing, we save it in the chain
lastData = @returnTypeOf(fn);
chain.push(@typeOf(fn));
} else {
// if it doesn't, we add the expected function to the
// chain, dump all the next functions, and return early
chain.push(expectedFunction, ...fns[index].map(@typeOf));
return chain;
}
}
return chain;
}; The @fn utils are something TypeScript can do as well, and so are conditional expressions and extracting tuple elements, that’s not an issue, but it looks like this code contains loops and mutations, which TypeScript cannot handle. It’s time to start converting our function to an FP-friendly way using recursion.
const expectedChain = (
fns,
previousReturn,
chain = [],
expectedFunction = (parameter: @typeOf(previousReturn)) => any,
headFunction = fns.head(),
tailFunctions = fns.tail(),
) =>
// check if we don't have other functions to test
fns.length == 0
// everything is fine and we return normally
? chain
// our condition inside the loop
: @extends(expectedFunction, @typeOf(headFunction))
// we call the function again after removing the first element of
// the functions, extract the expected data, and save the function
// we're currently testing
? expectedChain(tailFunctions, @returnTypeOf(headFunction), [
...chain,
@typeOf(headFunction),
])
// and this is our early return
: [...chain, expectedFunction, ...tailFunctions.map(@typeOf)];This code does exactly the same thing as the previous one, but it dropped the mutations and the loops. It’s also starting to look like proper TypeScript already!
Before writing the type, I check for helpers I might need and create them.
Let’s define what helpers we need and what they do:
-
Head– gets the first element of a tuple. -
Tail– gets all elements of a tuple except the head. -
Last– gets the last element of a tuple. -
Fn– will be our base function.
type Head<BaseArray extends readonly any[]> = BaseArray extends readonly [
infer FirstElement,
...infer _,
]
? FirstElement
: never;
type Tail<BaseArray extends readonly any[]> = BaseArray extends readonly [
infer _,
...infer Rest,
]
? Rest
: never;
type Last<BaseArray extends readonly any[]> = BaseArray extends readonly [
...infer _,
infer LastElement,
]
? LastElement
: never;
type Fn = (...args: any[]) => any;I convert the pseudo-code to actual TypeScript code and make it fit the rest of the code.
Now we have everything we need to translate our pseudo-code in TypeScript.
type CreateChain<
Fns extends readonly Fn[],
PreviousReturn,
Chain extends readonly Fn[] = [],
ExpectedFunction extends Fn = (parameter: PreviousReturn) => any,
HeadFunction extends Fn = Head<Fns>,
TailFunctions extends readonly Fn[] = Tail<Fns>,
> = Fns extends readonly []
? Chain
: HeadFunction extends ExpectedFunction
? CreateChain<
TailFunctions,
ReturnType<HeadFunction>,
[...Chain, HeadFunction]
>
: [...Chain, ExpectedFunction, ...TailFunctions]; Would you look at that! It’s almost a one-to-one translation of the pseudo-code! Now let’s plug this helper into our pipe function, and see how it goes.
declare const pipe: <const Value, const Fns extends readonly Fn[]>(
value: Value,
...fns: Fns extends CreateChain<NoInfer<Fns>, NoInfer<Value>>
? Fns
: CreateChain<NoInfer<Fns>, NoInfer<Value>>
) => ReturnType<Last<NoInfer<Fns>>>;At this point I look for improvements and edge-cases the type might not cover.
There’s only one little thing still bugging me: we invoke CreateChain twice. There isn’t much we can do about it tho; if we assign it to a generic type parameter, then when a function is not chainable, TypeScript would mark as an error all the functions, giving only the index as a reference. That makes it difficult to understand where the error is and provides a bad developer experience.
To test our code, let’s declare some utilities:
declare const double: (n: number) => number;
declare const square: (n: number) => number;
declare const formatNumber: (n: number) => string;
declare const uppercase: (s: string) => string;
declare const stringLength: (s: string) => number;Now let’s see our pipe in action:
const const a: stringa = const pipe: <8, [(s: string) => string, (n: number) => number, (n: number) => number, (n: number) => string]>(value: 8, fns_0: (parameter: 8) => any, fns_1: (n: number) => number, fns_2: (n: number) => number, fns_3: (n: number) => string) => stringpipe(8, uppercase, const double: (n: number) => numberdouble, const square: (n: number) => numbersquare, const formatNumber: (n: number) => stringformatNumber);const const b: stringb = const pipe: <8, [(n: number) => number, (s: string) => string, (n: number) => number, (n: number) => string]>(value: 8, fns_0: (n: number) => number, fns_1: (parameter: number) => any, fns_2: (n: number) => number, fns_3: (n: number) => string) => stringpipe(8, const double: (n: number) => numberdouble, uppercase, const square: (n: number) => numbersquare, const formatNumber: (n: number) => stringformatNumber);const const c: stringc = const pipe: <8, [(n: number) => number, (n: number) => number, (s: string) => string, (n: number) => string]>(value: 8, fns_0: (n: number) => number, fns_1: (n: number) => number, fns_2: (parameter: number) => any, fns_3: (n: number) => string) => stringpipe(8, const double: (n: number) => numberdouble, const square: (n: number) => numbersquare, uppercase, const formatNumber: (n: number) => stringformatNumber);const const d: stringd = const pipe: <8, [(n: number) => number, (n: number) => number, (n: number) => string, (s: string) => string]>(value: 8, fns_0: (n: number) => number, fns_1: (n: number) => number, fns_2: (n: number) => string, fns_3: (s: string) => string) => stringpipe(8, const double: (n: number) => numberdouble, const square: (n: number) => numbersquare, const formatNumber: (n: number) => stringformatNumber, const uppercase: (s: string) => stringuppercase);
const const e: numbere = const pipe: <"hello!", [(s: string) => number, (n: number) => number, (n: number) => number]>(value: "hello!", fns_0: (s: string) => number, fns_1: (n: number) => number, fns_2: (n: number) => number) => numberpipe("hello!", const stringLength: (s: string) => numberstringLength, const double: (n: number) => numberdouble, const square: (n: number) => numbersquare);All the errors are in the right place and the inferred output is correct, this means we’re done. Awesome!
Bonus Point
As I said in the beginning, a pipe is an input provided to the result of a function composition. This means we can also create a compose function with this type quite easily:
declare const compose: <
const Fns extends readonly Fn[],
Value = ReturnType<Head<Fns>>,
>(
...fns: Fns extends CreateChain<NoInfer<Fns>, NoInfer<Value>>
? Fns
: CreateChain<NoInfer<Fns>, NoInfer<Value>>
) => (parameter: Value) => ReturnType<Last<NoInfer<Fns>>>;And to test it out:
const const transformNumber: (parameter: number) => stringtransformNumber = const compose: <[(n: number) => number, (n: number) => number, (n: number) => string, (s: string) => string], number>(fns_0: (n: number) => number, fns_1: (n: number) => number, fns_2: (n: number) => string, fns_3: (s: string) => string) => (parameter: number) => stringcompose(const double: (n: number) => numberdouble, const square: (n: number) => numbersquare, const formatNumber: (n: number) => stringformatNumber, const uppercase: (s: string) => stringuppercase);
Conclusion
Creating complex TypeScript types can be daunting, but with a methodical approach, even the most intricate problems can be broken down into manageable steps. In this article, we’ve started from a simple implementation and gradually enhanced it.
If you take away anything from this article, please remember these points:
- Start simple: begin with a basic, untyped or minimally typed implementation. This helps you focus on the logic and understand the data flow before diving into wilder types.
- Use type utilities: advanced TypeScript features like
NoInfercan help you control type inference in complex scenarios, ensuring that types are inferred from the correct context and improving the accuracy of your types. - Iterative refinements: as your understanding of the problem deepens, refine your types iteratively. Don’t be afraid to start over or rethink your approach if the initial solution is not working as expected. I’ve done this dozens of times myself!
- Consider performance: while complex types can be fun to create, they can also become performance hogs; sometimes, the simpler solution might be better, even if it doesn’t tick all the boxes or seems tedious at first.
- Don’t be afraid to try new techniques: innovation comes from people that are not afraid to try and fail (or succeed!). There’s no single correct way to type your code, so try approaching problems from different perspectives.
As you gain more experience, you’ll develop an intuition for when and how to apply patterns and techniques you’ve already used before. The TypeScript type system will become as familiar and intuitive as any other programming language.
Please note that the overloading method is used by popular libraries like Remeda and there’s nothing wrong with it. In fact, I think it’s the most performant method.