Version 0.2.0 is now released. Download.
The major new feature is support for Like-constraints.
This is one of my favorite features. It allows us to declare what a parameter (or return value) should look like rather than what class it should be or descend from. This is a critical feature if we want to integrate classic JavaScript with typed ECMAScript 4 without having to rewrite everything at once.
Consider this. We have a point-type (with members x and y), and a function that operates on it:
var point1 = {x:10,y:20};
function sum(point) {
return point.x + point.y;
}
Now we might want to make the sum-function more type-safe. We could do that by declaring the structural type of the argument:
function sum(point : {x:int,y:int}) {
return point.x + point.y;
}
Now we are sure that no one accidentally call the functions with the wrong type of argument.
We could make it more explicit by defining a named type:
type Point = {x:int,y:int};
function sum(point : Point) {
return point.x + point.y;
}
So far so good. However now the type is constrained to only accept a record. A point could be expressed in other ways, eg. using a class:
class ClsPoint {
var x : int;
var y : int;
function ClsPoint(_x : int, _y : int)
: x=_x, y=_y {}
}
var point2 = new ClsPoint(10, 20);
or as a traditional JavaScript object:
function JsPoint(x : int, y : int) {
this.x = x;
this.y = y;
}
var point3 = new JsPoint(10, 20);
However, both of these will be rejected as arguments to sum, because they are not strictly of the same type as Point, which is declared as a record type.
"Like" to the rescue. If we define the function like this:
function sum(point like Point) {
return point.x + point.y;
}
The type system will check if the argument looks like Point, that is, has members with the same names and types as Point. Now all three types of objects will be accepted, since they all have the required x and y properties.
This is very cool, because it allows us to bridge the new classes, classic JavaScript constructors and pure structures (like what you get through JSON) in the same type system.
tirsdag den 17. juni 2008
Abonner på:
Kommentarer til indlægget (Atom)
This blog has moved to http://blog.mascaraengine.com. See you!
This blog is (was) for news, announcements and questions regarding the
Mascara ECMAScript 6 -> JavaScript translator.
This blog is (was) for news, announcements and questions regarding the
Mascara ECMAScript 6 -> JavaScript translator.
Ingen kommentarer:
Send en kommentar