首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当作为变量类型时,接口和InstanceType<typeof Class>有什么不同?

当作为变量类型时,接口和InstanceType<typeof Class>有什么不同?
EN

Stack Overflow用户
提问于 2019-09-30 16:33:26
回答 1查看 66关注 0票数 0

例如:

HttpService.ts

代码语言:javascript
复制
export interface IHttpService {
  request(): Promise<any>;
  formPostRequest(): any;
}

export class HttpService implements IHttpService {
  public async request() {
    //
  }

  public formPostRequest() {
    //
  }
}

现在,我将根据依赖注入使用HttpService。如下所示:

GoogleAccount.ts

代码语言:javascript
复制
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的类型,如下所示:

代码语言:javascript
复制
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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-30 16:52:55

我同意,如果你知道你需要实现的底层接口,那么就没有必要使用InstanceType<typeof HttpService>。InstanceType的使用应该限制在不能直接获取底层类型的情况下。这里有一些很好的Link用例

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58164186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档