Properties and ES3

Topics: Language Specification
Oct 2, 2012 at 6:29 PM
Edited Oct 2, 2012 at 6:41 PM

I'm a little disappointed that I need to --target ES5 in order for tsc to compile code that includes get/set properties. This implies that my "targeted" code would not work in IE6/7/8/9 and other less modern browsers.

I think being able to use properties unrestricted in TypeScript would be absolutely key toward the goal of "large-scale application maintainability".

Couldn't TypeScript compile this:

get name() { ... }
set name(value) { ... }

...to something like this for ES3:

Person.prototype.__getName = function () { ... }
Person.prototype.__setName = function (value) { ... }

This would allow me to easily port, for example, the Microsoft Media Platform Player Framework from WinJS to HTML5 in the browser, since we absolutely rely on classes w/ properties for maintainability in this project.

Coordinator
Oct 2, 2012 at 6:45 PM

Unfortunately, there's just not a way to support this at runtime in a way that's safe.

What you're proposing would be something like this:
(TypeScript)
var p = new Person('bob');
var name = p.name;
(Output JavaScript)
var name = p.__getName();

Note that the only reason we know to do the name -> __getName() translation is because we statically know the type of 'p'. While that's a (generally) safe assumption in C#, it's definitely not safe in an optionally-typed language like TypeScript.

Consider:
var p: any;
/* somewhere else: p  = new Person('bob'); */
var name = p.name; // What type is p? We don't know, so we don't know that we would need to transform to __getName()

Because the compiler can't (in the general case) know the type of every single expression in the program, it's impossible to make this sort of transormation work safely. It's much better to be up front about that limitation than to have a feature that only worked if you never accessed the member through a non-typed instance (a condition we can't statically check for).

Oct 2, 2012 at 7:02 PM

Just to be clear.  IE9 does support defineProperty:

http://kangax.github.com/es5-compat-table/#showold

I understand the issue, but it's disappointing that there's no workaround to target older browsers.

Oct 2, 2012 at 7:04 PM

I knew it wouldn't be easy, but if we didn't ask, then you might not realize it was that important. :)

I'm sure you guys have thought about this a lot already, but it still seems possible somehow, even if safety is compromised in rare cases. In C#, your example code var p: any; var name = p.name; would require a cast, so maybe you can invent some casting syntax and require the dev to use it to call p.name in that case.