例如:
HttpService.ts
:
export interface IHttpService {
request(): Promise<any>;
formPostRequest(): any;
}
export class HttpService implements IHttpService {
public async request() {
//
}
public formPostRequest() {
//
}
}
现在,我将根据依赖项注入使用HttpService
。像这样:
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();
}
}
以上代码将InstanceType
的typeof
和TypeScript
预定义类型用作httpService
的类型>
我经常使用的另一种方法是将interface
用作httpService
的类型,如下所示:
import { IHttpService } from './HttpService'; class GoogleAccount2 { private httpService: IHttpService; constructor(httpService: IHttpService) { this.httpService = httpService; } public findGoogleAccountById(id: string) { return this.httpService.request(); } }
两者都在
TypeScript
的类型系统下正常工作。tsc
没有投诉类型错误。那么,当作为静态类型的变量时,它们之间有什么区别?
也许在这种情况下不必使用InstanceType<typeof HttpService>
?
例如:HttpService.ts:导出接口IHttpService {request():Promise
我同意没有必要使用InstanceType<typeof HttpService>
,如果您知道需要实现的基础接口。InstanceType的用法应限于无法直接获取基础类型的情况。这里有一些很好的用例Link