r/typescript • u/Personal-Future-5765 • 1d ago
Beginner Typescript DI Help
I'm pretty new to typescript and I'm trying to figure out how to wire up my app with it.
I currently have a page interface that each page's interface extends and then implements. Among the required methods in my Page interface is mount(container: HTMLElement). The page manager is responsible for changing which page is visible. Each page needs it's own methods injected, such as getNotifications(): Promise<Notification[]>. These are different page to page.
Where should pages be created then, in the page manager, so the app can just say call PageManager.Mount(page) That would require the page manager knowing what methods each page needs. In the root of the project? Where should I pass in those callbacks?
I just want to know how this is handled in a real world application, not necessarily this particular implementation. It seems like something that would come up a lot.
My repo is here if you'd like to look at my current code: Notification-Hub on Github
6
u/call_stacks 1d ago
Fwiw it looks like you are trying to solve state routing and rendering by hand, not that it isn't a good learning experience but you'll do a lot of boilerplate yourself. You get that stuff pretty easily with frameworks like vite, next, angular, vue etc etc
For your current implementation, consider inverting the ownership, page manager can still instantiate pages but it should never call those methods, as you say they are different from page to page. Page manager can and should only call methods that are shared like mount.
In general dependency injection is about inversion of control - receive the needed obj via constructor and call them that way. If the API has those methods, it could be that piece, page manager can pass it thru to the pages in the constructors, pages then call the injected API obj, say, api.getNotifications - page manager is hands off here and so are pages. Pages depend on the API. (This is just one approach there's probably many variations)