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();
}
}
上面的代码使用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>
在这种情况下没有必要使用?
解决方案
我同意没有必要使用InstanceType<typeof HttpService>
如果你知道你需要实现的底层接口。InstanceType 的使用应仅限于无法直接获取基础类型的情况。这里有一些很好的用例链接
推荐阅读
- python - Django图像未上传
- javascript - 无法按字母顺序自动对按钮进行排序
- mysql - Sequelize $ne 没有像预期的那样工作
- jquery - 水平滚动时,DataTables Fixed Column 上的 Popover 看起来很奇怪
- node.js - 将 AppService 连接到虚拟机
- python - 有没有办法像基于图像的示例一样调整 CNN 的非图像文件的大小?
- javascript - Fancybox 忽略拇指选项
- c# - 点网的 Splunk 配置
- sqlite - 未触发 TypeORM 挂钩,包括最小项目
- java - 在 VSCode 中编译 java 类