非线性模式<a class="headerlink" href="#non-linear-pattern" title="Link to this heading">¶</a>
ID: js/non-linear-pattern
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- reliability
- correctness
- language-features
Query suites:
- javascript-security-and-quality.qls
如果同一个模式变量在同一个对象或数组模式中被绑定多次,则最后一次绑定将覆盖所有之前的绑定。这很可能是无意的,应该避免。
在 TypeScript 中,常见的错误是尝试在模式内编写类型注解。这是不可能的,类型注解应该放在模式之后。
建议<a class="headerlink" href="#recommendation" title="Link to this heading">¶</a>
将模式变量重命名为不同的名称。在数组模式中,可以省略不需要绑定的元素。
示例<a class="headerlink" href="#example" title="Link to this heading">¶</a>
在下面的示例中,函数<code class="docutils literal notranslate"><span class="pre">distanceFromOrigin</span></code>使用数组模式来分解其参数
<code class="docutils literal notranslate"><span class="pre">point</span></code>。该模式绑定
<code class="docutils literal notranslate"><span class="pre">x</span></code>两次:首先,
<code class="docutils literal notranslate"><span class="pre">x</span></code>绑定到
<code class="docutils literal notranslate"><span class="pre">point[0]</span></code>,即
<code class="docutils literal notranslate"><span class="pre">point</span></code>的第一个元素;然后,该绑定立即被绑定到
<code class="docutils literal notranslate"><span class="pre">point[1]</span></code>的绑定覆盖,这可能是无意的。
function distanceFromOrigin(point) {
var [x, x] = point;
return Math.sqrt(x*x + y*y);
}
从上下文来看,第二个绑定应该是针对变量<code class="docutils literal notranslate"><span class="pre">y</span></code>的,就像这样
function distanceFromOrigin(point) {
var [x, y] = point;
return Math.sqrt(x*x + y*y);
}
这有时会发生在 TypeScript 中,因为属性模式和类型注解表面上很相似。在下面的示例中,该函数使用一个具有属性<code class="docutils literal notranslate"><span class="pre">x</span></code>和
<code class="docutils literal notranslate"><span class="pre">y</span></code>的模式参数。这些属性看起来类型为
<code class="docutils literal notranslate"><span class="pre">number</span></code>,但实际上是无类型的属性,都存储在一个名为
<code class="docutils literal notranslate"><span class="pre">number</span></code>的变量中。
function distance({x: number, y: number}) {
return Math.sqrt(x*x + y*y);
}
在模式中不能指定类型注解。正确的方法是在参数之后指定类型
function distance({x, y}: {x: number, y: number}) {
return Math.sqrt(x*x + y*y);
}
参考资料<a class="headerlink" href="#references" title="Link to this heading">¶</a>
Mozilla 开发者网络:<a class="reference external" href="https://mdn.org.cn/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>。