Let's take a look at an example implementation:
HttpService.ts
:
export interface IHttpService {
request(): Promise<any>;
formPostRequest(): any;
}
export class HttpService implements IHttpService {
public async request() {
// Implementation goes here
}
public formPostRequest() {
// Implementation goes here
}
}
Now, let's see how we can use HttpService
with dependency injection. Here's an example:
GoogleAccount.ts
:
import { HttpService } from './HttpService';
class GoogleAccount {
private httpService: InstanceType<typeof HttpService>;
constructor(httpService: InstanceType<typeof HttpService>) {
this.httpService = httpService;
}
public findGoogleAccountById(id: string) {
return this.httpService.request();
}
}
The code above utilizes InstanceType
and typeof
, which are predefined types in TypeScript
.
Another approach I often use is to define the type of httpService
using an interface
. Here's how it looks:
import { IHttpService } from './HttpService';
class GoogleAccount2 {
private httpService: IHttpService;
constructor(httpService: IHttpService) {
this.httpService = httpService;
}
public findGoogleAccountById(id: string) {
return this.httpService.request();
}
}
Both methods work seamlessly within the TypeScript
type system without any complaints from tsc
. However, is using
InstanceType<typeof HttpService>
really necessary for this scenario?