Suggestion; When returning an interface, only return required methods and properties

Topics: General, Language Specification
Jun 10, 2013 at 11:14 AM
Edited Jun 10, 2013 at 11:14 AM
Currently when returning an interface, if the return object is this the translated code is simply this. I was wondering if there were any plans, or previous thoughts, with regards to returning only the required methods and properties of this, and constructing an anonymous object?

For example:
interface IPerson {
    id: number;
    name: string;
}

class Person implements IPerson {
    id: number = 0;
    name: string = '';
    hairColour: string = '';

    constructor() { }
    public getInfo(): IPerson {
        return this;
    }
}
Currently compiles to:
Person.prototype.getInfo = function () {
    return this;
};
Instead, my suggested approach would be:
Person.prototype.getInfo = function () {
    return {
        id: this.id,
        name: this.name
    };
};
The reasoning; this would particularly come in handy when overriding certain methods such as toJSON. Thoughts?
Coordinator
Jun 11, 2013 at 6:32 PM
This sort of aggressive guessing is not something we would do.

You can get the desired behavior very easily:
function makeShallowCopy(obj: Object) {
    var result = {};
    Object.getOwnPropertyNames(obj).forEach(name => result[name] = obj[name]);
    return result;
}

class Person implements IPerson {
    id: number = 0;
    name: string = '';
    hairColour: string = '';

    constructor() { }
    public getInfo(): IPerson {
        return makeShallowCopy(this);
    }
}
Jun 11, 2013 at 7:08 PM
Are there any languages that do what you're proposing (i.e. create a copy of certain properties of the object when assigned to a value of a supertype)?

Andrew Gaspar