如何根据 TypeScript 中的接口文件定义创建对象? [英] How can I create an object based on an interface file definition in TypeScript?

查看:41
本文介绍了如何根据 TypeScript 中的接口文件定义创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have defined an interface like this:

interface IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;
 }

我定义了一个这样的变量:

I define a variable like this:

var modal: IModal;

但是,当我尝试设置 modal 的属性时,它给了我一条消息

However, when I try to set the property of modal it gives me a message saying that

"cannot set property content of undefined"

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

Is it okay to use an interface to describe my modal object and if so how should I create it?

推荐答案

如果你在别处创建modal"变量,并想告诉 TypeScript 一切都会完成,你可以使用:

If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare const modal: IModal;

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

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

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

或者说谎,使用类型断言,但是您将失去类型安全性,因为您现在将在访问 modal.content 等(属性合同上说会在那里).

Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content and so on (properties that the contract says will be there).

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 接口的唯一实现,您可能希望完全删除该接口并使用...

You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...

const modal: Modal = new Modal();

而不是

const modal: IModal = new Modal();

这篇关于如何根据 TypeScript 中的接口文件定义创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆