Gary Sieling

TypeScript class example

One of the nice features of Typescript is that you can create classes. Now that ES6 also has this, it’s a little less impressive than it used to be, but lets take a look at what it lets use do:

class Dialog {
    title: String = "Test Title";
    message: String;
   
    constructor(message: String) {
        this.message = message;    
    }
     
    render() {
        console.log(this.title);
        console.log(this.message); 
    }
}

let d: Dialog = new Dialog("Test Message");

Note that we have constructors, properties with types, and we can set default values for types. You can use public/private as well, but they are only enforced by the compiler.

Here, you can see an example with inheritance:

class AlertDialog extends Dialog {
     render() {
         console.log("Alert"); 
     }    
}

let ad: Dialog = new AlertDialog("alert message");
ad.render();
Exit mobile version