简体   繁体   English

为什么浏览器可以理解此代码段,但我的打字稿编译器却不明白?

[英]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. 当我自己执行此操作时,我的打字稿编译器抛出了一个错误,“错误TS2554:预期为1-3个参数,但为0。”,这是有道理的。 The Array function .fill() requires at least one parameter. 数组函数.fill()至少需要一个参数。 When logging the array to the browser's console I see that 100 random numbers have actually been generated and mapped into array. 当将数组记录到浏览器的控制台时,我看到实际上已经生成了100个随机数并将其映射到数组中。 This is where my confusion starts. 这就是我开始困惑的地方。

I do have some thoughts... I am targeting es5 in my tsconfig. 我确实有一些想法...我的目标是tsconfig中的es5。 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. 对我来说有意义的是,.fill()的实现在ES6中已更改,并且浏览器能够理解代码,因为它没有违反ES6标准,但是打字稿编译器正在针对ES5进行验证,因为它确实违反了标准。

Just explicitly pass undefined instead of passing it implicitly: 只是显式传递undefined而不是隐式传递:

  .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. 它不是JavaScript错误,因为JS会隐式传递undefined ,但TS中的一个错误提示您隐式传递的参数对可读性不利。


By the way, a oneliner: 顺便说一句,oneliner:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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