【问题标题】:Query about interfaces in typescript查询打字稿中的接口
【发布时间】:2017-11-20 11:12:02
【问题描述】:

我已经开始学习来自 JavaScript 的 TypeScript,并且正在学习接口的工作原理。

我创建了以下名为 IEmailable 的界面:

interface IEmailable { name: string, email: string }

使用以下名为 sendEmail 的函数传递一个形状为 IEmailable 的对象:

function sendEmail(contact: IEmailable){
  console.log(contact.name + " <" + contact.email + ">"); }
}

所以,运行这个:

sendEmail({ 
   name: "Ciaran", 
   email: "ciaran.w@touchcreative.co.uk       
});

有效。

而运行这个:

sendEmail({ 
   name: "Ciaran", 
   email: "ciaran.w@touchcreative.co.uk,
   phone: 07927382
});

无效。

在我的 IDE 中,向接口中不存在的实例化对象添加新属性会引发错误。

“对象字面量只能指定已知属性”

所以我知道添加未在接口中定义的属性是无法完成的。但是,在我遵循的教程中 - 它指出可以添加新属性,并且在他们的 IDE 中没有引发错误。这是 TypeScript 的最新更新,还是我误解了 TypeScript 中接口的工作方式。我搜索了官方docs,在他们的示例中,他们实际上确实添加了一个新属性size,该属性在接口LabeledValue 中不存在。我肯定是想多了,但如果有人能解决这个问题,那就太好了。

【问题讨论】:

  • 您可以使用类型断言来避免 Object literals 的“过度属性检查”。在下面检查我的代码。

标签: javascript typescript interface


【解决方案1】:

根据文档

Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error.

因此下面的代码将导致错误,因为接口phone不存在IEmailable

sendEmail({ 
   name: "Ciaran", 
   email: "ciaran.w@touchcreative.co.uk,
   phone: 07927382
});

但是你可以通过使用下面的类型断言来绕过它

  sendEmail({ 
   name: "Ciaran", 
   email: "ciaran.w@touchcreative.co.uk",
   phone: 7927382
} as IEmailable);

否则,您可以向接口添加字符串索引签名,以确保对象可以具有一些额外的属性,您可以将其作为参数传递,如下所示

interface IEmailable { 
    name: string, 
    email: string,
    [propName: string]: any; 
 }

这是小提琴的有效链接。

"Fiddle"

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2019-06-01
    • 2016-04-04
    • 1970-01-01
    • 2020-08-14
    • 2019-05-04
    相关资源
    最近更新 更多