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 Xolv.io 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

Schedule a 30m call
  • Adding TypeScript to the official Apollo Platform Tutorial app

    In todays video I go through a preparation of the official Apollo Platform Tutorial App for adding Chimp to it. I decided to divide that task into two steps - first is adding TypeScript to the codebase. Watch me work, struggle, fly through code, hopefully you will learn some tricks :)

  • AWS CDK Lambda and DynamoDB dependency management

    A discussion about issues we've stumbled upon and a solution that simplified our CDK workflow.

  • cypress-cucumber-preprocessor 4.1.0 - TSX and Multiline Step Arguments support

    We've just released a new version of the cypress-cucumber-preprocessor package with TSX/React testing and Multiline Step Arguments.