【问题标题】:Reference module when overloading a global function in Typescript在 Typescript 中重载全局函数时的引用模块
【发布时间】:2019-05-23 06:26:05
【问题描述】:

我正在使用moment.js(特别是moment-timezone),它有一个名为Duration 的接口。 Duration.prototype.valueOf() 返回一个数字,所以在 JavaScript 中,调用

setInterval(myCallback, moment.duration(30, 'seconds'));

工作得很好。

我想编写一个允许这样做的 TypeScript 声明文件。

global.d.ts

export {};

declare global {
    function setTimeout(callback: (...args: any[]) => void, ms: Duration, ...args: any[]): NodeJS.Timeout;

    function setInterval(callback: (...args: any[]) => void, ms: Duration, ...args: any[]): NodeJS.Timeout;
}

当我添加

import { Duration } from 'moment-timezone';

它将 .d.ts 文件视为模块声明,因此不会影响全局命名空间。

我想将import 移动到declare global 范围内,但它仍然将Duration 视为any

我也试过

/// <reference path="node_modules/@types/moment-timezone/index.d.ts" />

但这似乎没有任何作用。

我看到一些答案提到了一些关于 tsconfig.json 中的设置的内容,但这对我来说不是一个选项,而且这看起来确实应该是一开始就可以实现的。

【问题讨论】:

    标签: typescript typescript-declarations


    【解决方案1】:

    这需要两个步骤:

    1. declare global 范围之外声明模块。
    2. imports 放在declare global 范围内。

    对于 OP 示例:

    export {}
    
    declare module 'moment-timezone';
    
    declare global {
        import { Duration } from 'moment-timezone';
    
        function setTimeout(callback: (...args: any[]) => void, ms: Duration, ...args: any[]): NodeJS.Timeout;
    
        function setInterval(callback: (...args: any[]) => void, ms: Duration, ...args: any[]): NodeJS.Timeout;
    }
    

    如果您想将自己的类型导入外部模块,请将import 放在declare module 范围内,并确保您的类型在它们自己的declare module 范围内。

    typings/my-custom-types.d.ts

    declare module 'my-custom-types' { // <-- this was the missing line that was giving me trouble
        export interface MyStringInterface {
            valueOf(): string;
        }
    }
    

    typings/some-lib/index.d.ts

    declare module 'some-lib' {
        import { MyStringInterface } from 'my-custom-types';
    
        export interface SomeExistingClass {
            // Add your own signatures
            someExistingMethod(stringParam: MyStringInterface): any;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多