I have defined an interface like this:
interface IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
Since I haven't found an equal answer in the top and my answer is different. I do:
modal: IModal = <IModal>{}
You can do
var modal = {} as IModal
If you want an empty object of an interface, you can do just:
var modal = <IModal>{};
The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:
class TestClass {
a: number;
b: string;
c: boolean;
}
compiles into
var TestClass = (function () {
function TestClass() {
}
return TestClass;
})();
which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.
If you are using React, the parser will choke on the traditional cast syntax so an alternative was introduced for use in .tsx files
let a = {} as MyInterface;
https://www.typescriptlang.org/docs/handbook/jsx.html
Using your interface you can do
class Modal() {
constructor(public iModal: IModal) {
//You now have access to all your interface variables using this.iModal object,
//you don't need to define the properties at all, constructor does it for you.
}
}
You can set default values using Class
.
interface IModal {
content: string;
form: string;
href: string;
isPopup: boolean;
};
class Modal implements IModal {
content = "";
form = "";
href: string; // will not be added to object
isPopup = true;
}
const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}
interface IModal {
content: string;
form: string;
href: string;
isPopup: boolean;
}
class Modal implements IModal {
constructor() {
this.content = "";
this.form = "";
this.isPopup = true;
}
content: string;
form: string;
href: string; // not part of constructor so will not be added to object
isPopup: boolean;
}
const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}