简体   繁体   English

d.ts文件中的Typescript迁移名称空间

[英]Typescript megring namespaces in d.ts files

Now I`m trying merge namespaces from d.ts Example: 现在,我正在尝试从d.ts示例合并名称空间:

When I tried megre namespaces in one file, all is well. 当我在一个文件中尝试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;

But when I moved first namespace to test.d.ts - all is brokes 但是,当我将第一个名称空间移到test.d.ts时,一切都坏了

test.d.ts test.d.ts

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

index.ts 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'.

I met this problem when I added new method to Electron, Angular2 and etc types. 当我向Electron,Angular2等类型添加新方法时遇到了这个问题。 Example: 例:

in electron/index.d.ts 电子/指数

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

in my file test.ts 在我的文件test.ts中

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

I got this error: TS2339: Property 'isQuiting' does not exist on type 'App'. 我收到此错误:TS2339:类型“ App”上不存在属性“ isQuiting”。

Do I can merge custom namespaces with d.ts ? 我可以将自定义名称空间与d.ts合并吗?

I think the problem is root import\\export in files: 我认为问题是文件中的root 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. 如果您在TypeScript文件的根级别进行导入或导出,则它将在该文件内创建本地作用域。

Read more here 在这里阅读更多

So the first file tst , and the second file tst in different scopes and can't be merged. 因此,第一个文件tst和第二个文件tst在不同的范围内并且不能合并。 You must remove all root import\\export from file, or move it to separated file. 您必须从文件中删除所有根import \\ export,或将其移到单独的文件中。

I found two solutions: 我发现了两种解决方案:

1) Remove all import/export from *.ts ( You can read about this here ) 1)从* .ts删除所有导入/导出( 您可以在此处阅读有关内容

2) Create new file *.d.ts (example test.extend.d.ts), write all cnanges into *.d.ts file, import this file: /// <reference path="*.d.ts" /> 2)创建新文件* .d.ts(例如test.extend.d.ts),将所有cnanges写入* .d.ts文件,然后导入该文件: /// <reference path="*.d.ts" />

Example: 例:

File: test.d.ts 文件: test.d.ts

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

File: test.ts 文件: test.ts

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM