查询typescript

时间:2017-11-20 11:12:03

标签: javascript typescript interface

我开始学习来自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中,向接口中不存在的实例化对象添加新属性会引发错误。

&#34;对象文字只能指定已知属性&#34;

所以我明白添加一个未在界面中定义的属性是不可能的。但是,在我遵循的教程中 - 它声明可以添加添加新属性,并且在IDE中不会抛出任何错误。这是对TypeScript的最新更新,还是我误解了接口在TypeScript中的工作方式。我搜索了官方docs,在他们的示例中,他们实际上添加了一个新的大小属性,该属性在 LabelledValue 中不存在>。我绝对会过度思考它,但如果有人能够明白这一点,那就太棒了。

1 个答案:

答案 0 :(得分:2)

根据文件

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"