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

How to import interface from type definitions (`.d.ts`) if it has generic parameter

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

/// <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 的类型允许定义自定义属性。所以,如果我们在拦截函数中写类似 file.customProperty = 1 的东西,就不会出现 TypeScript 错误。但是,对于自动完成,我想扩展 Vynyl 接口并重写类型,例如:

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行有错误:

TS2314: Generic type `VinylFile__PossiblyWithCustomProperties` requires 1 argument(s).

这里,我们不知道,会用到哪个Vynil超集,所以我不确定declare var intercept: intercept.Intercept<Vynil>;将是正确的。

我不确定,如果我已经完全理解了这个案例,但是如果你只是想让这个例子编译,在Intercept 的功能级别而不是顶级接口声明的一部分:

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;

客户端中的示例调用:

type ExtendedFile = Vinyl & { foo: string };

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

intercept(callback);