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);

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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