首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果接口具有泛型参数,如何从类型定义(`.d.ts`)导入接口

如果接口具有泛型参数,如何从类型定义(`.d.ts`)导入接口
EN

Stack Overflow用户
提问于 2019-12-17 10:15:25
回答 1查看 142关注 0票数 0

下面是提出这个问题时gulp-intercept的类型定义:

代码语言:javascript
复制
/// <reference types="node" />

import Vinyl = require('vinyl');

declare namespace intercept {
    interface Intercept {
        (interceptFunction: InterceptFunction): NodeJS.ReadWriteStream;
    }

    interface InterceptFunction {
        (file: Vinyl): Vinyl;
    }
}

declare var intercept: intercept.Intercept;

export = intercept;

Vynil的Typings允许定义自定义属性。因此,如果我们在intercept函数中编写类似file.customProperty = 1的代码,就不会出现TypeScript错误。然而,对于自动完成,我想扩展Vynyl接口并重写类型,如:

代码语言:javascript
复制
import Vinyl = require('vinyl');

declare namespace intercept {
    interface Intercept<VinylFile__PossiblyWithCustomProperties extends Vinyl> {
        (interceptFunction: InterceptFunction<VinylFile__PossiblyWithCustomProperties>): NodeJS.ReadWriteStream;
    }

    interface InterceptFunction<VinylFile__PossiblyWithCustomProperties extends Vinyl> {
        (file: VinylFile__PossiblyWithCustomProperties): VinylFile__PossiblyWithCustomProperties;
    }
}

declare var intercept: intercept.Intercept;

export = intercept;

declare var intercept: intercept.Intercept中有错误

代码语言:javascript
复制
TS2314: Generic type `VinylFile__PossiblyWithCustomProperties` requires 1 argument(s).

在这里,我们不知道将使用哪个Vynil超集,因此我不确定declare var intercept: intercept.Intercept<Vynil>;是否正确。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-21 08:57:42

我不确定我是否完全理解了这种情况,但如果您只是想编译这个示例,请在Intercept的函数级别注释类型参数VinylFile__PossiblyWithCustomProperties (在下面重命名为T ),而不是作为顶级接口声明的一部分:

代码语言:javascript
复制
import Vinyl = require("vinyl");

declare namespace intercept {
  interface Intercept {
    // annotate type parameter T directly at function
    <T extends Vinyl>(interceptFunction: InterceptFunction<T>): NodeJS.ReadWriteStream;
  }

  interface InterceptFunction<T extends Vinyl> {
    (file: T): T;
  }
}

declare var intercept: intercept.Intercept;

export = intercept;

客户端中的调用示例:

代码语言:javascript
复制
type ExtendedFile = Vinyl & { foo: string };

declare const callback: (file: ExtendedFile) => ExtendedFile;

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

https://stackoverflow.com/questions/59366722

复制
相关文章

相似问题

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