Skip to content

Instantly share code, notes, and snippets.

@brunokrebs
Created August 19, 2018 16:45
Show Gist options
  • Save brunokrebs/88cd578c8a835872fbaf313bb0c8f742 to your computer and use it in GitHub Desktop.
Save brunokrebs/88cd578c8a835872fbaf313bb0c8f742 to your computer and use it in GitHub Desktop.
Playing with TypeScript Generics
class GossipService {
gossip(message: string) {
console.log(message.toLowerCase());
}
}
export default GossipService;
import serviceLocator from './ServiceLocator';
import ScreamService from './ScreamService';
import GossipService from './GossipService';
serviceLocator.register('ScreamService', new ScreamService());
serviceLocator.register('GossipService', new GossipService());
const screamService = serviceLocator.get<ScreamService>('ScreamService');
screamService.scream('I like yelling');
const gossipService = serviceLocator.get<GossipService>('GossipService');
gossipService.gossip('I PREFER GOSSIPING');
class ScreamService {
scream(message: string) {
console.error(message.toUpperCase());
}
}
export default ScreamService;
class ServiceLocator {
private dependencyMap = {};
clear() {
this.dependencyMap = {};
}
get<T>(dependencyName): T {
return this.dependencyMap[dependencyName];
}
register<T>(dependencyName, constructor: T) {
this.dependencyMap[dependencyName] = constructor;
}
}
const serviceLocator = new ServiceLocator();
export default serviceLocator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment