如何在不同的文件中添加TypeScript函数重载

时间:2017-05-30 14:24:09

标签: typescript

我有一个Typescript模块,它包含对大型第三方API的调用(名称被混淆以保护无辜/有罪)。

// MyFile.ApiLib.ts
export module ApiLib {
    export function executeAction<TRequest, TResponse>(actionName: string, data: TRequest): Promise<TResponse>{
        ...
    }
}

此API的消费者可以创建自己的&#34;操作&#34;,因此我希望他们能够创建过载:

// MyFile.ApiLib.ts
export module ApiLib {
    export interface TheirRequestInterface { ... }
    export interface TheirResponseInterface { ... }

    export function executeAction<TheirRequestInterface, TheirResponseInterface>(actionName: "TheirActionName", data: TheirRequestInterface): Promise<TheirResponseInterface>;
    export function executeAction<TRequest, TResponse>(actionName: string, data: TRequest): Promise<TResponse>{
        ...
    }
}

但显然,他们不应该改变我的档案。我可以看到他们用自己的模块包装我的模块然后允许输入:

// TheirFile.ApiLib.ts
import { ApiLib } from "MyFile.ApiLib";

export module ApiLibWrapper {
    export interface TheirRequestInterface { ... }
    export interface TheirResponseInterface { ... }

    export function executeAction<TheirRequestInterface, TheirResponseInterface>(actionName: "TheirActionName", data: TheirRequestInterface): Promise<TheirResponseInterface>;
    export function executeAction<TRequest, TResponse>(actionName: string, data: TRequest): Promise<TResponse>{
        return ApiLib.executeAction<TRequest, TResponse>(actionName, data);
    }
}

但这意味着必须下载到浏览器的附加文件。我在跳,他们可以使用&#34; d.ts&#34;文件提供自己的定义,但在尝试引用Ts文件和&#34; d.ts&#34;文件,&#34; d.ts&#34;文件,它不会引入&#34; d.ts&#34;中定义的任何重载/接口。文件:

// TheirFile.ts
/// <reference path="CustomActionDefinitions.d.ts" />
import { ApiLib } from "MyFile.ApiLib";

ApiLib.executeAction(/* no overloads from the "d.ts" file shows up here */);

这可能吗?有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

看起来你想要的是增加一个名称空间(以前称为&#34;内部模块&#34;),它们已被模块导出(以前称为&#34;外部模块& #34;。)

我会声明如下:

// ./MyFile.ApiLib.ts
export namespace ApiLib {
    export function executeAction<TRequest, TResponse>(actionName: string, data: TRequest): Promise<TResponse>{
        /*...*/
    }
}

// TheirFile.ts
import "./MyFile.ApiLib";

// This is a module augmentation.
declare module "./MyFile.ApiLib" {

    // Within our module augmentation, we are reopening the namespace.
    export namespace ApiLib {
        export interface TheirRequestInterface { /*...*/ }
        export interface TheirResponseInterface { /*...*/ }

        // We are adding a new overload to 'executeAction'.
        export function executeAction<TheirRequestInterface, TheirResponseInterface>(actionName: "TheirActionName", data: TheirRequestInterface): Promise<TheirResponseInterface>;
    }
}