Last active
December 23, 2024 08:10
-
-
Save hmetgundogdu/4084cc55c049ecdfa1bd35e38ff92da7 to your computer and use it in GitHub Desktop.
Basically dependency injection in typescript
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 ICustomerService from './ICustomerService'; | |
| class CustomerService implements ICustomerService { | |
| getCustomers(): { username: string; email: string; }[] { | |
| throw new Error("Method not implemented."); | |
| } | |
| }; | |
| export default CustomerService; |
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
| interface Customer { | |
| username: string, | |
| email: string, | |
| } | |
| interface ICustomerService { | |
| getCustomers() : Customer[]; | |
| }; | |
| export default ICustomerService; |
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
| function inject <IService> (type : { new() : IService } ) { | |
| return new type(); | |
| } | |
| export default inject; |
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 { inject } from './Inject'; | |
| import ICustomerService from './ICustomerService' | |
| import CustomerService from './CustomerService' | |
| function main () { | |
| const instance = inject<ICustomerService>(CustomerService); | |
| const allCustomers = instance.getCustomers(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment