Typescript和Uncaught SyntaxError:在严格模式之外尚不支持块范围的声明(let,const,function,class)

o..*_*..o 3 javascript uncaught-exception typescript visual-studio-2015

我有一个包含类定义的打字稿文件:

if (window.console == null) {
    (<any>window).console = {
            error: function (a) {
        },
            log: function (a) {
        }
    };
}

class SendMessage {
    //.....
}
Run Code Online (Sandbox Code Playgroud)

在编译为javascript(通过VS2015)之后,我在类定义的行上得到了错误:

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
Run Code Online (Sandbox Code Playgroud)

我发现我必须使用严格模式.但为什么以及如何在打字稿中使用它呢?

谢谢

Dav*_*ret 11

这是因为它正在编译ES6,浏览器要求在严格模式下使用块范围的声明.

您可以使用严格模式来解决此问题.为此,添加......

"use strict";
Run Code Online (Sandbox Code Playgroud)

...到每个文件的顶部.

但是,我认为您可能希望将编译目标从ES6更改为ES5.如果您正在使用tsconfig.json,请更改"target": "es6""target": "es5".这样做...将编译为ES5 ...因此块大小的声明将被适当更改,因此"use strict";不需要.此外,更多浏览器将支持您的代码.目前,运行时ES6支持仍然不普遍.

请注意,如果您不使用tsconfig.json,则可能必须在项目属性的typescript构建选项卡中更改目标,如下所示:

ECMAScript版本更改