javascript - 为什么我可以将未知属性分配给 typescript 中的文字对象?

标签 javascript reactjs angular typescript

  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/

相关文章:

javascript - 在 reactjs 中为 tensorflowjs 加载 model.json 不起作用

javascript - 将外部 JS 导入 Angular 8

angular - 带有 Angular 提交功能的 Google 日历 API

javascript - 如何检查用户并通过然后重定向

javascript - 在 Javascript 对象中返回键和值

javascript - 如何使用 ReactJS 将输入值保存到文本文件?

angular - 如何在 Angular 6 中以 JSON 格式发送从数据库创建的动态字段的数据

javascript - 如何在我自己的应用程序中包含对库的更改?

reactjs - React Redux Store 更新,但组件未重新渲染

javascript - 如何在 react 中通过 Prop 导入图像并使用 'import' 路径