Friday 4 January 2013

Typescript objects


Required:
You need to have installed Typescript or have a way to test it.

You can try it here: http://www.typescriptlang.org/Playground/

// Interface that will be implemnted
interface IPerson {
    //definition of  variables
    FullName: string;
    GetName: string;
    // definition of a function
    GetFullName(): string;
}

interface IDeveloper {
    GetRole(): string;
}

//definition of class that Implements person
class Person implements IPerson {
    FullName: string;
    GetName: string;
    // constructor
    constructor(public name: string) {
        this.FullName = name;
    }
 
    // implemnetation of methods
    GetFullName() {
        return this.FullName;
    }
}
 
 
class Developer extends Person  implements IDeveloper{
    GetRole() {
        return "Developer";
    }
}
 
//example
 
var dev = new Developer("MyName");
alert(dev.GetFullName() + dev.GetRole()) 
 
//example will fail  
var dev = new Developer(1);
alert(dev.GetFullName() + dev.GetRole())


rendered code by typescript


var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Person = (function () {
    function Person(name) {
        this.name = name;
        this.FullName = name;
    }
    Person.prototype.GetFullName = function () {
        return this.FullName;
    };
    return Person;
})();
var Developer = (function (_super) {
    __extends(Developer, _super);
    function Developer() {
        _super.apply(this, arguments);

    }
    Developer.prototype.GetRole = function () {
        return "Developer";
    };
    return Developer;
})(Person);
var dev = new Developer("MyName");
alert(dev.GetFullName() + dev.GetRole());


Returning specific type:

In function I want to have specific return type. I have found this implementation:

function FunctionName(parameter1: string, callback: (result: string) => any){...}
which is specific return type for method that has multiple returns, and we can specify each type that can be returned.

for our example the return objects are:

1, string
2, any object

No comments:

Post a Comment