Back to articles
Dependency Injection in TypeScript: Stop Hardcoding Your Dependencies

Dependency Injection in TypeScript: Stop Hardcoding Your Dependencies

via Dev.to WebdevYoung Gao

Dependency Injection in TypeScript: Stop Hardcoding Your Dependencies Every time you write new DatabaseClient() inside a service, you are welding that service to a specific implementation. Testing requires a real database. Swapping providers means rewriting code. Dependency injection fixes this. Constructor Injection interface Logger { info ( msg : string ): void ; error ( msg : string , err ?: Error ): void ; } interface UserRepository { findById ( id : string ): Promise < User | null > ; save ( user : User ): Promise < void > ; } class UserService { constructor ( private readonly users : UserRepository , private readonly logger : Logger ) {} async getUser ( id : string ): Promise < User > { this . logger . info ( `Fetching user ${ id } ` ); const user = await this . users . findById ( id ); if ( ! user ) throw new Error ( " User not found " ); return user ; } } UserService does not know if it is talking to Postgres, MongoDB, or an in-memory store. It does not care. Wiring It Together

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
7 views

Related Articles