jcroll
jcroll

Reputation: 7165

Is there any way to enforce the type of an uninstantiated class?

Is there any way in typescript to enforce the type of an uninstantiated class?

Below I want to enforce that only classes that extend Repository can be passed to the addRepository method but I do not want to instantiate the class when being passed in (its constructor should be only be called by the service container).

Is there any way to do this?

import { Repository } from '../repositories/repository';

class Factory {

  addRepository(repositoryClass: Repository) /* <- seriously what can go here? */ { }
}

class UserRepository extends Repository {

}

let factory = new Factory();

factory.addRepository(UserRepository); // throws error

Upvotes: 0

Views: 165

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52213

You can use the typeof operator:

class Factory {
  addRepository(repositoryClass: typeof Repository) { }
}

Upvotes: 2

Related Questions