简体   繁体   中英

Why does the browser understand this snippet, but my typescript compiler doesn't?

I was reading through someone else's code when I came across this snippet.

let array = Array(100)
   .fill()
   .map(_ => { 
       return Math.floor(Math.random() * 100 + 1)) 
   });

When implementing this on my own, my typescript compiler threw an error, "error TS2554: Expected 1-3 arguments, but got 0.", which makes sense. The Array function .fill() requires at least one parameter. When logging the array to the browser's console I see that 100 random numbers have actually been generated and mapped into array. This is where my confusion starts.

I do have some thoughts... I am targeting es5 in my tsconfig. What would make sense to me is that the implementation of .fill() changed in ES6, and the browser is able to understand the code because it doesn't violate ES6 standards, but the typescript compiler is validating against ES5, where it does violate the standard.

Just explicitly pass undefined instead of passing it implicitly:

  .fill(undefined)

Its not a JavaScript error as JS would implicitly pass undefined , but one from TS hinting you that implicitly passed arguments are a bad thing for readability.


By the way, a oneliner:

  const array = Array.from({ length: 100 }, () => Math.floor(Math.random() * 100 + 1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM