5

TypeScript doesn't allow the with statement from JavaScript.

var radius = 12;
with (Math) {
    var area = PI * radius * radius;
}

The explanation is that it isn't allowed in "strict mode" in ECMAscript 5.

Is this just the with statement - or is anything disallowed by "strict mode" also not allowed in TypeScript?

1 Answer 1

6

TypeScript does allow the with statement, as not doing so would violate its being a superset of JavaScript. However, the compiler will emit an error (though still compiles and outputs code), because there is no way for anything to know anything about what is being referenced from a with statement except at runtime, which completely defeats the purpose of static typing, so you shouldn’t be using it in a TypeScript program. There’s an additional discussion on the TypeScript forum about this.

With regards to other strict mode things not allowed in TypeScript, since TypeScript tries to follow the ES6 specification where it can for its new features, and the ES6 specification (§10.2.1) says “Module code is always strict code.” and “A ClassDeclaration or a ClassExpression is always strict code.”, you will probably find that nearly all your TypeScript code will need to conform to strict mode at some point in the future, if not today.

Sign up to request clarification or add additional context in comments.

5 Comments

It doesn't really allow it - it emits an error and the specification says "Use of the 'with' statememt in TypeScript is an error." - as always, the compiler attempts to give you code even when errors are present. Thanks for the ES6 reference though - it does seem likely that TypeScript will align with those definitions.
Yeah, I guess it depends a bit on how you want to define ‘allow’; the compiler will output code, but it will also always emit an error. So it works while it fails. ¯\(°_o)/¯
"there is no way for anything to know anything about what is being referenced from a with statement " -- well: If with would support a generics-like syntax, it would be possible to know everything at compile time: For example with<{x: number}>({x: 5}) { a = x + 5 } --- and Algorithm W would be perfectly fine to resolve such statements
@GarlefWegart I think the problem with your proposal is that the generic's type is only resolved at type checking time, but the compiler will need the names of its members in the binder stage (prior to type checking).
All well and good banning this unless you want to write a javascript interpreter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.