Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I assign unknown properties to literal object in 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
  }

The typescript code is as above, my question is that isn't the last three lines the same? Why the first line can pass and the second line get a complaint, and the third line get a pass?

Also on the typescript playground: playground

like image 479
nolan Avatar asked Jul 21 '20 01:07

nolan


1 Answers

After some research, I found the answer is in TypeScript's document.

So the difference between the last 3 lines is that: The param in the 2nd line is object literally, while the other 2 not, TypeScript treat literally params and non-literally params differently:

Excess Property Checks

like image 51
nolan Avatar answered Oct 20 '22 01:10

nolan