javascript - 当对象类型不匹配时,对于泛型函数不会出现编译错误

标签 javascript typescript compilation typescript-generics

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

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

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

type Simple = { a: string };

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

以下运行正常

typed<Simple>(fields);

但这会导致编译错误:

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

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

typescript 版本:3.5.3

Playground 链接: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 ,但是对象文字有附加属性 b以及a .

解决方案-

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

关于javascript - 当对象类型不匹配时,对于泛型函数不会出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57808893/

相关文章:

javascript - AngularJS:具有不同属性的对象数组中的 ngIf

javascript - 在 Rails 应用程序中使用液体模板语言变量动态更改站点的 css

angular - 在 rxjs/ngrx 效果中链接 Action 的正确方法是什么

typescript - cdk CI/CD 管道 - 销毁重复堆栈

json - 从 Typescript 解析 JSON 恢复数据成员但不是类型 : cannot call methods on result

Javascript:不同的返回类型

c++ - 在 C++ 应用程序中构建/编译 libcurl 时遇到问题

java - 将类转换为不相关的接口(interface)

c - 制作库: conflicting types in header and source file

javascript - Firefox 与 typed.js 不兼容?