简体   繁体   English

Typescript 带扩展语法的接口

[英]Typescript interface with spread syntax

I was trying to make an interface and initialize its instance with another object properties by spread syntax.我试图创建一个接口并通过扩展语法用另一个 object 属性初始化它的实例。 I found something weird and wanted to find out why this can happen.我发现了一些奇怪的东西,想找出为什么会发生这种情况。

This is an example of what I want.这是我想要的例子。

A : The object that I want to make as a result A : 结果我想做的object

A = {  a: number, b: number, c: number, d: number }

B : The object I've got with DB query B :我通过数据库查询获得的 object

B = {a: number,b: number,c: number,e: string}

C : The object that has a value I will insert manually C :具有我将手动插入的值的 object

C = { d: boolean }

So I've declared an interface A, and used spread syntax to make an object of A with B object.所以我已经声明了一个接口 A,并使用扩展语法来制作 A 的 object 和 B object。

A_object = {...B_object }

What I expected was an object of A which has properties 'a', 'b', and 'c', or an error.我期望的是 A 的 object,它具有属性“a”、“b”和“c”,或者一个错误。 But the result was quite different.但结果却截然不同。 Property 'e' also appeared, which doesn't exist in interface A.属性 'e' 也出现了,它在接口 A 中不存在。
Can anybody explain why this happens?谁能解释为什么会这样?

测试截图

The spread operator is a JavaScript feature which does not know about the known properties of TypeScript-interfaces.扩展运算符是一个 JavaScript 功能,它不知道 TypeScript 接口的已知属性。 All properties of B_object will therefore appear in A_object when A_object = {...B_object } .因此,当A_object = {...B_object }时, B_object所有属性都将出现在A_object中。

From a type-safety perspective, this is fine.从类型安全的角度来看,这很好。 Everything needed to construct a valid A instance is also present in B , so spreading B into A is considered to be valid.构造有效A实例所需的一切也存在于B中,因此将B扩展到A被认为是有效的。

You are probably looking for excess property checks .您可能正在寻找多余的财产支票 Those are not necessarily needed in a structural type system and there are only a select few places where TypeScript does perform them.这些在结构类型系统中不一定需要,并且只有 select 很少的地方 TypeScript 执行它们。 And spreading objects is not one of those places.传播物体不是那些地方之一。 There is an open Issue requesting this and you can give it a thumbs up if you want to see it implemented.有一个未解决的问题要求这样做,如果你想看到它的实现,你可以竖起大拇指。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM