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

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"

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


当前回答

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

let a = {} as MyInterface;

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

其他回答

实际上,创建对象并不需要类。你可以直接这样做:

interface IModal {
    content: string;
    form: string;
}

onButtonSaveClick() {
    let myModalClass: IModal = {
        content: 'foo content',
        form: 'foo form'
    }
}

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

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

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

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

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

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

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

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

let a = {} as MyInterface;

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

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

modal: IModal = <IModal>{}
let deletedQuestionsDto = { examId: this.examId, questionId: q.id } as DeletedQuestionsDto;