接口和InstanceType 作为变量类型有什么区别?

问题描述 投票:0回答:1

例如:

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();
  }
}

以上代码将InstanceTypetypeofTypeScript预定义类型用作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 ; formPostRequest():任意; }出口类HttpService实现IHttpService {public async request()...

typescript
1个回答
1
投票

我同意没有必要使用InstanceType<typeof HttpService>,如果您知道需要实现的基础接口。InstanceType的用法应限于无法直接获取基础类型的情况。这里有一些很好的用例Link

© www.soinside.com 2019 - 2024. All rights reserved.