type ExpectedType = Array<{ name: number, gender?: string }>
function go1(p: ExpectedType) {
}
function f() {
const a = [{name: 1, age: 2}]
go1(a) // doesn't complain
go1([{name: 1, age: 2}]) // complain 'Object literal may only specify known...'
go1(['no matter'].map(n => ({name: 1, age: 2}))) // doesn't complain
}
typescript 代码如上,我的问题是最后三行不一样吗?为什么一线可以通过,二线投诉,三线通过?同样在 typescript 操场上:
playground
最佳答案
将 var a 分配给 go1() 的参数时,似乎将变量 a 分配给另一个 para 变量。在这种情况下,因为 a 的类型与参数变量类型兼容。但是如果将类型更改为 { name: number, 性别:字符串 },你仍然会有类型错误。
当分配一个字面量对象作为参数时,这种情况下没有类型转换,因此编译器可以检测到这种类型错误。
更多详情请引用 here .
The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x. For example:
interface Named {
name: string;
}
let x: Named;
// y's inferred type is { name: string; location: string; }
let y = { name: "Alice", location: "Seattle" };
x = y;
To check whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y. In this case, y must have a member called name that is a string. It does, so the assignment is allowed.
关于javascript - 为什么我可以将未知属性分配给 typescript 中的文字对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005960/