多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## UMD 库 既可以通过`<script>`标签引入,又可以通过`import`导入的库,称为 UMD 库 ts 提供了一个新语法`export as namespace` ## export as namespace ``` // types/foo/index.d.ts export as namespace foo; export = foo; declare function foo(): string; declare namespace foo { const bar: number; } ``` 也可与`export default` 一起使用 ``` export as namespace foo; export default foo; declare function foo(): string; declare namespace foo { const bar: number; } ``` ## 直接扩展全局变量§ ``` interface String { prependHello(): string; } // 'foo'.prependHello(); ``` 通过声明合并,使用`interface String`即可给`String`添加属性或方法。 ## 在 npm 包或 UMD 库中扩展全局变量 对于 npm 包或 UMD 库,如果导入此库之后会扩展全局变量,则需要使用另一种语法在声明文件中扩展全局变量的类型,那就是`declare global`。 #### `declare global`[§](https://ts.xcatliu.com/basics/declaration-files.html#declare-global) 使用`declare global`可以在 npm 包或者 UMD 库的声明文件中扩展全局变量的类型[25](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/25-declare-global): ``` // types/foo/index.d.ts declare global { interface String { prependHello(): string; } } export {}; ``` ``` // src/index.ts 'bar'.prependHello(); ``` 注意即使此声明文件不需要导出任何东西,仍然需要导出一个空对象,用来告诉编译器这是一个模块的声明文件,而不是一个全局变量的声明文件。