当对象类型不匹配时,泛型函数没有编译错误

No compilation error when for generic funciton when object types do not match

考虑以下不执行任何操作的通用函数:

const typed = <T>(fields: T) => {}

然后我们定义以下类型和变量:

type Simple = { a: string };

const fields = { a: "", b: "" };

以下是运行正确

typed<Simple>(fields);

但这会导致编译错误:

typed<Simple>({ a: "", b: "" });

在这两种情况下,输入类型相同,但第二个示例失败了(应该如此)。为什么第一个案例有效?

打字稿版本:3.5.3

游乐场link:https://www.typescriptlang.org/play/#code/MYewdgzgLgBFCeAHApgExgXhgHgCoD4AKAMwEtkAbVCALhlwEpN8YBvAXwFgAoHhFGAGVSAW0QVkmNjACGdaACdSYAOYx2Abh6hIsMpWpTWsugCJTAGhgAjM6fVbe3APTO4AC1IQYoMaQkQfEho2MJiEkT6VBAMjjyuHl4+MgCuEMjevoj+MlCk4DDICgogCkEoqKGi4shExnIw5la2jfbssTxAA

当您将 object literals 作为参数传递时,它们会进行额外的 属性 检查 - https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks.

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:

只能通过对象字面量传递已知属性。 simple 类型只有 属性 a,但是对象字面量除了 a.

之外还有其他 属性 b

解决方案-

typed<Simple>({ a: "", b: "" } as Simple);