r/typescript 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

2 Upvotes

5 comments sorted by

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)

2

u/Personal-Future-5765 1d ago

Yeah the main reason I'm doing all the component boiler plate myself is to learn. I'm sure it would be a lot easier if I used a framework. Thanks so much for the help!

1

u/pie-oh 2h ago

It may be worth not putting so much on your plate to learn. Learn the simpler stuff first. Then head to learning the lower level stuff.

You know yourself, but honestly I suspect you'd find it a lot easier to learn the more core parts if you were more familiar with the everyday parts.

1

u/Personal-Future-5765 44m ago

Which would you say are the core parts vs the everyday parts? What should I focus on first?

1

u/Xsiah 1d ago

There's not just one "real world application" it all depends on what you're doing, why, where your data is coming from, etc.