Enriched Descriptors, maybe ES7 ?
Andrea Giammarchi
andrea.giammarchi at gmail.com
Sun Mar 9 14:25:47 PDT 2014
As written before, and explained in the project, I can write descriptors
with optional extra properties such as:
**type**, describing as string the typeof, as Function the expected
instanceof, or as generic object as prototypeOf(expectedType)
```javascript
var o = {};
Object.defineProperty(o, 'num', {
value: 0,
type: 'number'
});
o.num = 123; // ok
o.num = '123'; // throws an error, '123' is string, not number
```
The meaning of type here is the same MS choose for TypeScript but no
breaking syntax is necessary plus types can be optionally used to described
methods or functions too.
```javascript
var o = {};
Object.defineProperty(o, 'increment', {
value: function (much) {
this.num += much;
return this;
},
arguments: ['number'], // 1 arg as number
returns: Object // just an instanceof object
});
o.num = 0;
o.increment(1).increment(2);
o.num; // 3
o.increment('1'); // thorws since the argument is not a typeof number
```
The received arguments can have overloads so that:
```javascript
var o = {};
Object.defineProperty(o, 'increment', {
value: function (much) {
this.num += parseFloat(much);
return this;
},
arguments: [['number'],['string']],
// 1 arg as number or 1 arg as string
returns: Object // just an instanceof object
});
o.num = 0;
o.increment(1).increment(2);
o.num; // 3
o.increment('1'); // OK
o.num; // 4
o.increment(new Number(1)); // throws, not typeof number/string
```
Either the amount of arguments is wrong or the type won't match ... the
signature is guarded during development time.
In production, you just do not include upfront the proposed script and
everything will work as regular ES5 preserving all behaviors and
descriptors ... in few words, I am proposing an alternative to TypeScript
that integrates well down to ES5.
If engines would like to use types and descriptors provide such info, this
could have ideally performance benefits too plus the code will be most
likely less "*undefined is not defined*" prone.
The library I have there, already provides all I've said behind 64 tests
that verify the behavior is guarded and preserved with or without the
library upfront.
Compatibility with the test link [here](
https://github.com/WebReflection/define-strict-properties#compatibility)
Best Regards
On Sun, Mar 9, 2014 at 2:05 PM, Brendan Eich <brendan at mozilla.com> wrote:
> Andrea Giammarchi wrote:
>
>> Although my idea is more about types
>>
>
> You are starting on the wrong foot there. "Types" mean something in CS.
> Best if you start with use-cases instead of abusing the term. What code do
> you want to write, and how exactly would it operate?
>
> /be
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140309/60d18ec6/attachment.html>
More information about the es-discuss
mailing list