Skip to content

Instantly share code, notes, and snippets.

@paolobueno
Created January 18, 2018 18:32
Show Gist options
  • Save paolobueno/01b7d8fe4cc417232cc2b801266eeea9 to your computer and use it in GitHub Desktop.
Save paolobueno/01b7d8fe4cc417232cc2b801266eeea9 to your computer and use it in GitHub Desktop.
Strong strings
class ServiceModule {}
class SyncService extends ServiceModule {}
class KeycloakService extends ServiceModule {}
type ServiceModuleConstructor<T extends ServiceModule> = new() => T;
class ServiceModuleRegistry {
private serviceTypeMap: {
[key: string]: ServiceModuleConstructor<ServiceModule>
} = {};
public getServiceClass(serviceType: "sync"): ServiceModuleConstructor<SyncService>
public getServiceClass(serviceType: "auth"): ServiceModuleConstructor<KeycloakService>
public getServiceClass(serviceType: string): ServiceModuleConstructor<ServiceModule> {
return this.serviceTypeMap[serviceType];
}
public register(type: "sync", moduleConstructor: ServiceModuleConstructor<SyncService>)
public register(type: "auth", moduleConstructor: ServiceModuleConstructor<KeycloakService>)
public register(type: string, moduleConstructor: ServiceModuleConstructor<ServiceModule>){
this.serviceTypeMap[type] = moduleConstructor;
}
}
const registry = new ServiceModuleRegistry();
registry.register("sync", SyncService);
const sync = new (registry.getServiceClass("sync"))();
console.log(sync.constructor.name); // SyncService, gets proper intellisense support
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment