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

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设置默认值。

没有类构造函数:

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 = <IModal>{};

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

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

编译成

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

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

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

let a = {} as MyInterface;

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

你可以这样做

var modal = {} as IModal 

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

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

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

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

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

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

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

如果你在其他地方创建了“modal”变量,并想告诉TypeScript它将全部完成,你可以使用:

declare const modal: IModal;

如果你想创建一个实际上是TypeScript中IModal实例的变量,你需要完整地定义它。

const modal: IModal = {
    content: '',
    form: '',
    href: '',
    $form: null,
    $message: null,
    $modal: null,
    $submits: null
};

或者撒谎,使用类型断言,但是你会失去类型安全,因为你现在会在意想不到的地方得到未定义,并且可能在访问modal时出现运行时错误。内容等(合同规定的属性)。

const modal = {} as IModal;

示例类

class Modal implements IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;
}

const modal = new Modal();

你可能会想“嘿,这真的是一个重复的界面”-你是正确的。如果Modal类是IModal接口的唯一实现,你可能想要删除整个接口并使用…

const modal: Modal = new Modal();

而不是

const modal: IModal = new Modal();