Typing a Function Composition with Overloads and Generics
This is a classic problem in TypeScript.
We start with a
compose function that spreads in an array of functions that take in an
input, and returns an output:
0:00 This is a classic problem in TypeScript, which is we have a compose function. This compose function takes in an array of functions basically spread in like this and then takes an input and then returns an output.
0:16 We have addOne and addTwoAndStringify. Basically, this one takes in a number and returns num + 1. Then addTwoAndStringify, it composes those two functions together. It's like addOne, addOne, and then uses the String constructor to basically turn it into a string. This result equals addTwoAndStringify. The result is equal to 6.
0:41 What this is doing is it's supposed to work on the type level too. Currently, this is typed as any, but, in fact, we want it typed as string because that's the result of this String function here. The stringifyThenAddOne function here, what it's doing is it's basically saying...
1:00 We've now got a conflict between two functions inside our system, which is this one, this String, takes in actually anything and returns a string, but it's passing it to addOne, which expects a number.
1:17 Whoo. We've got a really complicated setup here, where you have a function which passes something to another function,passes something to another function. You need to find a way to strongly type this. There is a way to strongly type this. It involves function overloads. You're going to need to capture quite a lot of information in generics here.
1:37 You're going to need to capture the thing that the first function takes in, what it returns, the thing that the second function takes in, what it returns, and the thing that the third function takes in and what it returns. You should be able to compose up to, let's say, five functions. In real life, this might go up to 10 or 20 or things like that. For now, let's just keep it to five.
2:00 I think that's all the information I'm going to give you. Function overloads are going to be critical here. Generics are going to be critical. You will end up with a solution that feels hacky too. The hacky solution is, in fact, the best solution on the market. Good luck.