例如:
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>?
发布于 2019-09-30 16:52:55
我同意,如果你知道你需要实现的底层接口,那么就没有必要使用InstanceType<typeof HttpService>。InstanceType的使用应该限制在不能直接获取底层类型的情况下。这里有一些很好的Link用例
https://stackoverflow.com/questions/58164186
复制相似问题