snippettypescriptCritical
How can I create an object based on an interface file definition in TypeScript?
Viewed 0 times
typescriptobjecthowdefinitioninterfacefilecanbasedcreate
Problem
I have defined an interface like this:
I define a variable like this:
However, when I try to set the property of modal it gives me a message saying that
Is it okay to use an interface to describe my modal object and if so how should I create it?
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"Is it okay to use an interface to describe my modal object and if so how should I create it?
Solution
If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:
If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.
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
Example Class
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...
Rather than
declare const 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.
const 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).const modal = {} as IModal;Example Class
class Modal implements IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
const 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...
const modal: Modal = new Modal();Rather than
const modal: IModal = new Modal();Code Snippets
declare const modal: IModal;const modal: IModal = {
content: '',
form: '',
href: '',
$form: null,
$message: null,
$modal: null,
$submits: null
};const modal = {} as IModal;class Modal implements IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
const modal = new Modal();const modal: Modal = new Modal();Context
Stack Overflow Q#13142635, score: 762
Revisions (0)
No revisions yet.