考虑以下不执行任何操作的通用函数:
const typed = <T>(fields: T) => {}
然后我们定义以下类型和变量:
type Simple = { a: string };
const fields = { a: "", b: "" };
以下运行正常
typed<Simple>(fields);
但这会导致编译错误:
typed<Simple>({ a: "", b: "" });
在这两种情况下,输入类型是相同的,但第二个示例失败了(正如它应该的那样)。为什么第一个案例有效?
typescript 版本:3.5.3
最佳答案
当您通过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/