我已经定义了一个这样的接口:
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"
是否可以使用接口来描述我的模态对象,如果是这样,我应该如何创建它?
这里是我经常使用的另一个解决方案。但是我不确定这是否是好的做法,如果不是,请在下面评论。
/// 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);
谢谢:)
如果你在其他地方创建了“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();