Better handling for namespace patterns in .js files

TypeScript 2.8 adds support for understanding more namespace patterns in .js files.Empty object literals declarations on top level, just like functions and classes, are now recognized as as namespace declarations in JavaScript.

  1. var ns = {}; // recognized as a declaration for a namespace `ns`
  2. ns.constant = 1; // recognized as a declaration for var `constant`

Assignments at the top-level should behave the same way; in other words, a var or const declaration is not required.

  1. app = {}; // does NOT need to be `var app = {}`
  2. app.C = class {
  3. };
  4. app.f = function() {
  5. };
  6. app.prop = 1;

IIFEs as namespace declarations

An IIFE returning a function, class or empty object literal, is also recognized as a namespace:

  1. var C = (function () {
  2. function C(n) {
  3. this.p = n;
  4. }
  5. return C;
  6. })();
  7. C.staticProperty = 1;

Defaulted declarations

“Defaulted declarations” allow initializers that reference the declared name in the left side of a logical or:

  1. my = window.my || {};
  2. my.app = my.app || {};

Prototype assignment

You can assign an object literal directly to the prototype property. Individual prototype assignments still work too:

  1. var C = function (p) {
  2. this.p = p;
  3. };
  4. C.prototype = {
  5. m() {
  6. console.log(this.p);
  7. }
  8. };
  9. C.prototype.q = function(r) {
  10. return this.p === r;
  11. };

Nested and merged declarations

Nesting works to any level now, and merges correctly across files. Previously neither was the case.

  1. var app = window.app || {};
  2. app.C = class { };