Skip to content

Instantly share code, notes, and snippets.

@Offirmo
Last active September 21, 2017 06:41
Show Gist options
  • Save Offirmo/9a54766bd067f9f619deebee68c0f632 to your computer and use it in GitHub Desktop.
Save Offirmo/9a54766bd067f9f619deebee68c0f632 to your computer and use it in GitHub Desktop.
[Simple TypeScript dependency injection] #tags: TypeScript
import { foo } from '../libs/foo'
import { bar } from './libs/bar'
interface InjectableDependencies {
logger: Console
foo: typeof foo
}
const defaultDependencies: InjectableDependencies = {
logger: console,
foo,
}
async function factory(dependencies: Partial<InjectableDependencies> = {}) {
const { foo, logger } = Object.assign({}, defaultDependencies, dependencies)
logger.log('Hello')
function doStuff(x): Promise<void> {
return foo().then(x => bar(x))
}
return {
doStuff,
}
}
// optional
const defaultInstance = factory()
const doStuff = defaultInstance.doStuff
export {
InjectableDependencies,
factory,
doStuff,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment