How to pass a class to a function in TypeScript
You can watch me go through this exercise here:
TypeScript documentation generously helps us with an example:
Fantastic! Looks easy enough... to copy and paste...
You (and also, me in the past, at least a few times), all excited, copy the createInstance function and start changing it to your liking, just to find out... it does not work!
Not only TypeScript complains, but the error is a not-so-helpful dead-end. Good luck googling "is not assignable to parameter type".:)
It turns out the fix is easy once you figure it out, but it's definitely not trivial. The simplified example from the TypeScript documentation had classes without constructors... because that's the most common case for how people use classes...? :) Anyway...
The trick is to tell TypeScript that it is indeed fine for a class to have a constructor, that also takes arguments, imagine that!
To do that change the new () => A
to new (...args) => A
, here how the new createInstance
function looks like:
So that is great. Remember the original example? Turns out we can change the createInstance
function argument type the same way, adding the ...args, and even their example still works (since ...args is fine with 0 arguments).
I can only wonder how many tortured souls went through this problem without a clue, and finally gave up.
Good luck there, TypeScripters :)
Let me know if you have any questions or thoughts in the comments below.