Mascara: Next Generation JavaScript compiler

Try it Download Buy About Documentation Blog Contact

Like

Like-constraints are a special kind of type constraint which allows us to declare what a parameter should look like rather than what class it should be or descend from.

Like-constraints can be used on function parameters and return types.

Example:

function area(box like {width:int,height:int}) {
    return box.width * box.height;
}

The parameter box is required to have two properties, height and width, both of type int. Whether box is actually a class instance or a structural type is not important.

Longer Example

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)
        : this.x=x, this.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.

X Try!
Mascara JavaScript Generated JavaScript

Translating...
Show compiler settings