Marilou Marilou - 6 months ago 27
TypeScript Question

How can I create an object based on an interface file definition in TypeScript?

I have defined an interface like this:

interface IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}


I define a variable like this:

var modal: IModal;


However when I try to set the property of modal it gives me a message saying that

"cannot set property content of undefined"


Can someone help me with this? Is it okay to use an interface to describe my modal object and if so how should I create it?

Answer Source

If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare var modal: IModal;

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

var modal: IModal = {
    content: '',
    form: '',
    href: '',
    $form: null,
    $message: null,
    $modal: null,
    $submits: null
};

Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content and so on (properties that the contract says will be there).

var modal = <IModal>{};

Example Class

class Modal implements IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;
}

var modal = new Modal();

You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...

var modal: Modal = new Modal();

Rather than

var modal: IModal = new Modal();