I am trying to create a container that I can use to register and get services, but when I try to access the service it is not found. It's like the compiler is ignoring my file and not including it because I'm only directly using the interfaces declared in it.
I have my service container/registry defined as follows:
// Services.ts
export abstract class Services {
private static container: {[key: string]: ICachedService | undefined} = {}
public static add = (key: string, serviceFactory: ServiceFactory): void => {
this.container[key] = {service: undefined, factory: serviceFactory}
}
public static get = <T>(key: string): T | undefined => {
const cachedService = Services.container[key]
if (cachedService) {
if (!cachedService.service) {
cachedService.service = new cachedService.factory()
}
return cachedService.service as T
}
return undefined
}
}
export type ServiceFactory = new () => IService
interface ICachedService {
service?: IService
factory: ServiceFactory
}
Then my service looks like this:
// MyService.ts
import {Services} from '../../../common/services/services'
export interface IMyService {
doSomething: () => void
}
export class MyService implements IMyService {
public doSomething = () => {
console.log('doSomething');
}
}
Services.add('MyService', MyService)
Then in my component I try to use my service (this is where it is always undefined):
// MyComponent.tsx
import {IMyService} from '../services/MyService'
export function MyComponent() {
const myService = Services.get<IMyService>('MyService')!
myService.doSomething() // myService is undefined
return (
<>
<div>Hello World</div>
</>
)
}
If I directly instantiate the service anywhere in the code like App.tsx by doing const myService = new MyService()
then the rest of the code works fine, but I'd ideally avoid having to do that. Is there any way to force the service code to be added to the output?