Created
August 19, 2018 16:45
-
-
Save brunokrebs/88cd578c8a835872fbaf313bb0c8f742 to your computer and use it in GitHub Desktop.
Playing with TypeScript Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GossipService { | |
gossip(message: string) { | |
console.log(message.toLowerCase()); | |
} | |
} | |
export default GossipService; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ScreamService { | |
scream(message: string) { | |
console.error(message.toUpperCase()); | |
} | |
} | |
export default ScreamService; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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