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

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"

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


当前回答

因为我没有在上面找到一个相等的答案,所以我的答案是不同的。 我做的事:

modal: IModal = <IModal>{}

其他回答

你可以这样做

var modal = {} as IModal 

使用你的界面就可以做到

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

这里是我经常使用的另一个解决方案。但是我不确定这是否是好的做法,如果不是,请在下面评论。

/// Interface
export default interface BookInterface {
  title: string,
  author: string,
  id: any
}

/// Creating Class
export class BookClass implements BookInterface {
  title: string;
  author: string;
  id: any;

  constructor(title: string, author: string, id: any) {
    this.title = title;
    this.author = author;
    this.id = id;
  }
}

/// How to use it
let book: BookInterface = new BookClass(title, author, id);

谢谢:)

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

let a = {} as MyInterface;

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

如果你想要一个空的接口对象,你可以这样做:

var modal = <IModal>{};

使用接口代替类来构造数据的优点是,如果类上没有任何方法,它将在编译后的JS中显示为空方法。例子:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

编译成

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

没有任何价值。另一方面,接口根本不会出现在JS中,同时仍然提供数据结构和类型检查的好处。