TypeScript interface example

TypeScript has a structure called interfaces, although they look like a struct and act like a duck type.

Observe (note you can put semicolons after the value declarations if you like):

interface Model {
    title: string
    contents: string
}

When using this, we can reference the values in code (and, Visual Studio code can do Intellisense on these)

class Dialog {
    render(data: Model) {
        console.log(data.contents)
    }
}

let dialog: Dialog = new Dialog()

However, you don’t have to instantiate the type – the keys just have to have the right names, so they are effectively duck typed.

dialog.render({
    title: "test title",
    contents: "contents"
}); 

If you wanted to declare a variable of type Model, you can also do this:

let x: Model = {
    title: "test",
    contents: "test contents"
 };

Note that you can’t instantiate the interface like you might in Java / Scala, or you’ll get this error:

test.ts(13,29): error TS1005: ',' expected.

Finally, the type checks only exist at compile time, resembling type erasure in Java. That said, this is incredible compared to Javascript.

The final compiled result of this shows the type erasure, like so:

var Dialog = (function () {
    function Dialog() {
    }
    Dialog.prototype.render = function (data) {
        console.log(data.title);
    };
    return Dialog;
}());
var x = {
    title: '123',
    contents: 'aaa'
};
var d = new Dialog();
d.render(x);

Leave a Reply

Your email address will not be published. Required fields are marked *