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

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"

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


当前回答

你可以这样做

var modal = {} as IModal 

其他回答

下面是另一种方法:

你可以像这样简单地创建一个ESLint友好的对象

const modal: IModal = {} as IModal;

或者基于接口的默认实例,如果有默认值的话

const defaultModal: IModal = {
    content: "",
    form: "",
    href: "",
    $form: {} as JQuery,
    $message: {} as JQuery,
    $modal: {} as JQuery,
    $submits: {} as JQuery
};

然后通过重写一些属性来改变默认实例

const confirmationModal: IModal = {
    ...defaultModal,     // all properties/values from defaultModal
    form: "confirmForm"  // override form only
}

使用你的界面就可以做到

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.
  }
}
let deletedQuestionsDto = { examId: this.examId, questionId: q.id } as DeletedQuestionsDto;

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

如果你正在使用React,解析器会被传统的强制转换语法阻塞,所以在.tsx文件中引入了一种替代方法

let a = {} as MyInterface;

https://www.typescriptlang.org/docs/handbook/jsx.html