为什么我可以在打字稿中为文字对象分配未知属性?

nol*_*lan 10 javascript typescript reactjs angular

  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
  }
Run Code Online (Sandbox Code Playgroud)

打字稿代码如上,我的问题是最后三行不一样吗?为什么第一行可以通过,第二行投诉,第三行通过?

同样在打字稿操场上: 操场

nol*_*lan 1

经过一番研究,我发现答案就在 TypeScript 的文档中。

所以最后 3 行之间的区别在于:第 2 行中的参数是字面上的对象,而其他 2 行不是,TypeScript 对待字面参数和非字面参数的方式不同:

超额财产检查