d.ts 文件中的 Typescript megring 命名空间

Typescript megring namespaces in d.ts files

现在我正在尝试合并来自 d.ts 的命名空间 示例:

当我在一个文件中尝试使用 megre 命名空间时,一切正常。

declare namespace tst {
    export interface info {
        info1: number;
    }
    var a: info;
}

declare namespace tst {
    export interface info {
        info2: number;
    }
}

tst.a.info1 = 1;
tst.a.info2 = 1;

但是当我将第一个命名空间移动到测试时。d.ts - 一切都崩溃了

测试.d.ts

declare namespace tst {
    export interface info {
        info1: number;
    }
    var a: info;
}

index.ts

/// <reference path="test.d.ts" />

declare namespace tst {
    export interface info {
        info2: number;
    }
}

// Module to control application life.
tst.a.info1 = 1;
tst.a.info2 = 1; // Error:(31, 7) TS2339: Property 'info2' does not exist on type 'info'.

我在向 Electron、Angular2 等类型添加新方法时遇到了这个问题。 示例:

electron/index.d.ts

declare namespace Electron {
    interface App extends NodeJS.EventEmitter {
        ...
    }
}

在我的文件中test.ts

declare namespace Electron {
    interface App extends NodeJS.EventEmitter {
        isQuiting?: boolean;
    }
}

我收到此错误:TS2339:属性 'isQuiting' 在类型 'App' 上不存在。

我可以将自定义名称空间与 d.ts 合并吗?

我认为问题出在根 import\export 文件中:

If you have an import or an export at the root level of a TypeScript file then it creates a local scope within that file.

Read more here

所以第一个文件tst和第二个文件tst在不同的范围内,不能合并。您必须从文件中删除所有根 import\export,或将其移动到单独的文件中。

我找到了两个解决方案:

1) 从 *.ts ()

中删除所有 import/export

2) 创建新文件 *.d.ts (例如 test.extend.d.ts), 将所有 cnanges 写入 *.d.ts 文件, 导入此文件:/// <reference path="*.d.ts" />

示例:

文件:测试。d.ts

declare namespace Electron {
    interface App extends NodeJS.EventEmitter {
        isQuiting?: boolean;
    }
}

文件:test.ts

/// <reference path="test.d.ts" />
import {...} from "..."; // Any import/export
app.isQuiting = false; // IT WORKS!!!
app.quit(); // types of electron work too!