【问题标题】:This condition will always return 'false' since the types 'string[]' and 'string' have no overlap. ts(2367) [closed]此条件将始终返回 'false',因为类型 'string[]' 和 'string' 没有重叠。 ts(2367) [关闭]
【发布时间】:2021-12-23 18:38:54
【问题描述】:

今天出现此错误时,我正在使用 Angular。我在Typescript error This condition will always return 'true' since the types have no overlap 上阅读了接受的答案,但我不知道它是什么意思。

模板:

<div class="container">
    Paste your text here: <textarea #count width="150" height="150"></textarea><br>
    <button class="btn btn-dark" (click)=check(count.value)>Count</button>
    <br>
    <p id="result"></p>
</div>

组件:

import { Component, OnInit } from '@angular/core';
// import { checkServerIdentity } from 'tls'; i don't exist!

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  check(text:string) {
    var counts:string[];
    counts = text.split(" ");
    let resultid = document.getElementById("result");
    if (counts === "" /* here error */) {
      // where i left over
    }
  }

}

错误:

This condition will always return \'false\' since the types \'string\[\]\' and \'string\' have no overlap. ts(2367)

【问题讨论】:

  • counts 是一个字符串数组,"" 是一个字符串,所以根本没有必要比较它们。他们永远不会平等。只需写 if (false) { 或完全删除该块。

标签: angular typescript


【解决方案1】:

您将counts 自己定义为string[],然后尝试将其与空字符串进行比较。字符串数组永远不会等于 any 字符串。

我不确定您对哪个部分感到困惑。错误再清楚不过了:您正在尝试将字符串数组与字符串进行比较。这两个永远不会相等,所以条件 counts === "" 将始终评估为 false,这可能是一个错误,所以 TypeScript 正确地告诉你要多加注意。编写条件始终为false 的条件if 是没有意义的——该代码永远不会运行,因此您需要删除整个块或更改条件。

【讨论】:

  • 谢谢我意识到我只需要在 if 中将“counts”更改为“text”
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 2020-12-11
  • 2020-01-05
  • 1970-01-01
相关资源
最近更新 更多