Search code examples
javascripttypescriptvisual-studio-2015uncaught-exception

Typescript and Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode


I have a typescript file containing a class definition:

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

class SendMessage {
    //.....
}

After the compilation to javascript (by VS2015), I get the error on the line with the class definition:

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

I have found that I have to use the strict mode. But why and how can I use it in typescript?

Thanks


Solution

  • It's because it's compiling to ES6 and the browser is requiring that block-scoped declarations be used in strict mode.

    You can fix this by using strict mode. To do that add...

    "use strict";
    

    ...to the top of every file.

    However, I think you probably want to change the compilation target from ES6 to ES5. If you are using tsconfig.json, change "target": "es6" to "target": "es5". Doing that will...compile to ES5...and so block-scoped declarations will be changed appropriately so "use strict"; will not be required. Additionally, more browsers will support your code. Right now runtime ES6 support is still not widespread.

    Note that if you are not using tsconfig.json, you might have to change the target in the project properties' typescript build tab as shown here:

    ECMAScript version change