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:

class BeeKeeper {
  hasMask: boolean;
}

class ZooKeeper {
  nametag: string;
}

class Animal {
  numLegs: number;
}

class Bee extends Animal {
  keeper: BeeKeeper;
}

class Lion extends Animal {
  keeper: ZooKeeper;
}

function createInstance<A extends Animal>(c: new () => A): A {
  return new c();
}

createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;

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!

abstract class User {  
  constructor(public id: string) {}  
}   
class Admin extends User {  
  doAdminThing() {}  
}  
  
class PaidMember extends User {  
  doPaidMemberThing() {}  
}  
  
function createInstance<A extends User>(c: new () => A): A {  
  return new c();  
}  
  
createInstance(Admin)
// ^ Error: Argument type Admin is not assignable to parameter type {new(): User} 

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:

function createInstance<A extends User>(c: new (...args) => A): A {  
  return new c();  
}
createInstance(Admin).doAdminThing() // TypeScript Happy!
createInstance(PaidMember).doPaidMemberThing() // TypeScript Happy!   
createInstance(PaidMember).doAdminThing() // TypeScript Sad.. But rightly so this time!

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

// ...
  
function createInstance<A extends Animal>(c: new (...args) => A): A {  
  return new c();  
}  
  
createInstance(Lion).keeper.nametag;  
createInstance(Bee).keeper.hasMask;

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.


Let us help you on your journey to Quality Faster

We at Xolvio specialize in helping our clients get more for less. We can get you to the holy grail of continuous deployment where every commit can go to production — and yes, even for large enterprises.

Feel free to schedule a call or send us a message below to see how we can help.

User icon
Envelope icon

or

Book a call
+
Loading Calendly widget...
  • Add types to your AWS lambda handler

    Lambdas handlers can be invoked with many different, but always complex, event arguments. Add to that the context, callback, matching return type and you basically start listing all the different ways that your function can fail in production.

  • How to expose a local service to the internet

    From time to time you might need to expose your locally running service to the external world - for example you might want to test a webhook that calls your service. To speed up the test/development feedback loop it would be great to be able to point that webhook to your local machine.

  • For loops in JavaScript (vs _.times)

    From time to time I still see a for loop in JavaScript codebases. Linters are frequently angry about them. Let's see how we can replace them.