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

后端 未结 11 1372
[愿得一人]
[愿得一人] 2020-12-04 05:01

I have defined an interface like this:

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


        
相关标签:
11条回答
  • 2020-12-04 05:46

    Since I haven't found an equal answer in the top and my answer is different. I do:

    modal: IModal = <IModal>{}
    
    0 讨论(0)
  • 2020-12-04 05:47

    You can do

    var modal = {} as IModal 
    
    0 讨论(0)
  • 2020-12-04 05:50

    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.

    0 讨论(0)
  • 2020-12-04 05:50

    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

    0 讨论(0)
  • 2020-12-04 05:51

    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.
      }
    }
    
    0 讨论(0)
  • 2020-12-04 05:53

    You can set default values using Class.

    Without Class Constructor:

    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}
    

    With Class Constructor

    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}
    
    0 讨论(0)
提交回复
热议问题