Skip to content

Instantly share code, notes, and snippets.

@Offirmo
Last active January 16, 2025 00:46
Show Gist options
  • Select an option

  • Save Offirmo/9a54766bd067f9f619deebee68c0f632 to your computer and use it in GitHub Desktop.

Select an option

Save Offirmo/9a54766bd067f9f619deebee68c0f632 to your computer and use it in GitHub Desktop.
[🔷TS -- Simple dependency injection] #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