什么时候作为一种变量?,typescript"/>

首页 > 解决方案 > Interface 和 InstanceType 有什么区别什么时候作为一种变量?

问题描述

例如:

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

上面的代码使用InstanceTypetypeof预定义的类型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>在这种情况下没有必要使用?

标签: typescript

解决方案


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


推荐阅读