我已经定义了一个这样的接口:

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

我这样定义一个变量:

var modal: IModal;

然而,当我尝试设置modal属性时,它会给我一个消息说

"cannot set property content of undefined"

是否可以使用接口来描述我的模态对象,如果是这样,我应该如何创建它?


当前回答

使用你的界面就可以做到

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.
  }
}

其他回答

使用你的界面就可以做到

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.
  }
}

您可以使用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}

你可以这样做

var modal = {} as IModal 

该界面有5种使用方式。

 interface IStudent {
          Id: number;
          name: string;
        }
        
        
        Method 1. all fields must assign data.
         const  obj1: IStudent = { Id: 1, name: 'Naveed' };  
        
        Method 2. my favorite one
        const obj2 = { name: 'Naveed' } as IStudent ;
        
        Method 3.
        const obj3 = <IStudent >{name: 'Naveed'}; 
        
        Method 4. use partial interface if all fields not required.
        const  obj4: Partial<IStudent > = { name: 'Naveed' };  
        
        Method 5. use ? Mark with interface fields if all fields not required.
        const  obj5: IStudent = {  name: 'Naveed' };  

目前发布的许多解决方案都使用类型断言,因此如果在实现中遗漏了所需的接口属性,也不会抛出编译错误。

对于那些对其他健壮、紧凑的解决方案感兴趣的人:

选项1:实例化一个实现接口的匿名类:

new class implements MyInterface {
  nameFirst = 'John';
  nameFamily = 'Smith';
}();

选项2:创建一个实用函数:

export function impl<I>(i: I) { return i; }

impl<MyInterface>({
  nameFirst: 'John';
  nameFamily: 'Smith';
})