TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Strange TypeScript Behavior

3 点作者 christian0cfg超过 4 年前
At Codesphere, we code mostly in Typescript, not necessarily because it is our favorite language, but because we found out that it made us the most productive.<p>However, recently I came across two very strange behaviors, (I know, they are common in the JavaScript Bubble) and I felt the urge to share them!<p>1: [&#x27;1&#x27;, &#x27;2&#x27;, &#x27;10&#x27;].map(parseInt); I came across this when I wanted to format some user input, convert it into numbers and put them in a chart.<p>Alt Text<p>[&#x27;1&#x27;, &#x27;2&#x27;, &#x27;10&#x27;].map(parseInt);<p>This does not work, because map passes three arguments into parseInt() on each iteration. The second argument index is passed into parseInt as a radix parameter. So each string in the array is parsed using a different radix. &#x27;2&#x27; is parsed as radix 1, which results in NaN, &#x27;10&#x27; is parsed as radix 2, which is 3, and &#x27;1&#x27; is parsed as the default radix 10 because its index 0 is falsy.<p>2: Inheritance of &#x27;readonly&#x27; in Typescript During a code review we came across the idea to make methods readonly. What happened next left us a little confused.<p>It&#x27;s actually not possible to make a method readonly, but it is possible to make a readonly property with a function type, which has the same effect.<p>Interestingly enough, it is not possible to assign the property again for instances of the same class, but it is possible to inherit a class and override the property, as well as, assign the property on an instance of a subclass.<p>class Roman { readonly jonas: () =&gt; void = () =&gt; console.log(&quot;huh?&quot;); }<p>class Elias extends Roman { jonas: () =&gt; void = () =&gt; console.log(&quot;oh no, override works!&quot;); }<p>const elias = new Elias(); elias.jonas(); &#x2F;&#x2F; oh no, override works! elias.jonas = () =&gt; console.log(&quot;oh no, assignment works too!&quot;); elias.jonas(); &#x2F;&#x2F; oh no, assignment works too!<p>What is your experience with Typescript? What do you find most confusing in Typescript?

1 comment

Raed667超过 4 年前
&gt; map passes three arguments into parseInt()<p>That is how it is supposed to work, that&#x27;s how it would also work in Java (and probably other languages but I don&#x27;t know)<p>You want to pass parameters to suit your particular need you pass them explicitly:<p><pre><code> [&#x27;1&#x27;, &#x27;2&#x27;, &#x27;10&#x27;].map(i =&gt; parseInt(i))</code></pre>
评论 #26041506 未加载