简体   繁体   English

为什么此lambda函数不是打字稿中的错误?

[英]Why is this lambda function not an error in typescript?

I imagined this code 我想像这段代码

let x: (a: { b: number }) => void = (a: { b: number, c: string }) => { alert(a.c) };
x({ b: 123 });

should produce an error, since the lambda function requires an additional property on the a argument, so the signatures should not be compatible. 应该会产生一个错误,因为lambda函数需要在a参数上附加一个属性,因此签名应该不兼容。 But trying this in the latest typescript playground does not produce any errors! 但是在最新的打字稿游乐场尝试此操作不会产生任何错误! Why is that? 这是为什么?

When you said 当你说

let x: (a: { b: number }) => void

You are saying "x is a function that takes an object with a b key." 您说的是“ x是一个带有b键的对象的函数”。

You then assigned it a lambda that took an object with a b key and a c key. 然后,您为其分配了一个lambda,该lambda带有一个对象,该对象带有b键和c键。 That passes the typechecker because any object that gets passed in must have a b key. 这样可以通过类型检查器,因为任何传入的对象都必须具有b键。

Then you pass it an object with a b key. 然后,使用b键向其传递对象。 There's no error. 没有错

If you want it to fail because of the c key, make the type of x the following: 如果您希望它由于c键而失败,则将x的类型设置为以下形式:

let x: (a: { b: number, c: string }) => void

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

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