生成冗余变量的Typescript
Typescript generating redundant variable
考虑以下Typescript代码:
module demoAppModule{
'use strict';
export module nest{
export var hello = function () {
alert('Hello!');
};
}
}
demoAppModule.nest.hello();
在传输后,我们有以下javascript代码:
var demoAppModule;
(function (demoAppModule) {
'use strict';
(function (nest) {
nest.hello = function () {
alert('Hello!');
};
})(demoAppModule.nest || (demoAppModule.nest = {}));
var nest = demoAppModule.nest;
})(demoAppModule || (demoAppModule = {}));
demoAppModule.nest.hello();
为什么生成此行?它伤了我的眼睛。
var nest = demoAppModule.nest;
简短回答:需要在本地访问模块变量。例如
module demoAppModule{
'use strict';
export module nest{
export var hello = function () {
alert('Hello!');
};
}
// The following would not be possible without that line
console.log(nest.hello);
}
demoAppModule.nest.hello();
更长的答案:它类似于在模块之前添加的var,例如注意var x
:
// TypeScript
module x{export var foo;}
// Generated JavaScript
var x;
(function (x) {
x.foo;
})(x || (x = {}));
但是,当您在模块内部+导出模块时,var
需要添加到outermodule.innermodule
,因此您不需要提前执行var innermodule
。您将其添加到outermodule
,然后创建一个本地变量指向innermodule
,您可以在生成的javascript:中看到它
// Notice var here
var demoAppModule;
(function (demoAppModule) {
'use strict';
// Notice no var here
(function (nest) {
nest.hello = function () {
alert('Hello!');
};
})(demoAppModule.nest || (demoAppModule.nest = {}));
// Notice var assinged afterwards
var nest = demoAppModule.nest;
// The following would not be possible without that line
console.log(nest.hello);
})(demoAppModule || (demoAppModule = {}));
demoAppModule.nest.hello();
相关文章:
- 如何在Typescript中的回调中访问类变量
- 循环完成后,Ionic2/TypeScript清除变量
- Angular2/Typescript:从链接可观察函数访问实例变量
- Typescript foreach变量不可用
- TypeScript:从类访问全局变量而不导入
- TypeScript:从模块创建全局变量
- 在 Typescript 中添加函数之前,如何将变量声明为空对象
- AngularJS,Typescript 通过服务传递变量
- 在 TypeScript 中使用外部模块声明一个全局变量
- Webpack bundle 和 TypeScript 产生错误的全局变量格式
- 默认导出为全局变量 Typescript 1.8 --module UMD
- 生成冗余变量的Typescript
- 使用类将JSON对象强制转换为typescript类型的变量的正确方法
- TypeScript:变量是在MVC页面上定义的
- TypeScript-NodeJS-意外的令牌'构造函数、函数、访问器或变量'
- 如何在Web API(MVC)中将多个变量从typescript(angular.js)传递给Controller
- TypeScript:类/方法中变量/属性的声明
- 为什么typescript允许在声明变量之前先使用它
- Typescript编译器/Cordova API:检查未定义的全局变量
- Typescript变量“”没有出现在当前作用域“”中