Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript TS2531:对象在.match()期间可能为“null”_Typescript - Fatal编程技术网

Typescript TS2531:对象在.match()期间可能为“null”

Typescript TS2531:对象在.match()期间可能为“null”,typescript,Typescript,在下面的代码中,我在fileNameMatches[0]上得到了标题错误linting。它不会忽略布尔检查。删除该支票不会修复或更改任何内容。有人知道如何解决这个问题吗 protected getLocalFilename(): string { const fileNameMatches: string[]|null = this.filePath.match(/\/(.+\.js)$`/); if (Boolean(fileNameMatches) &&

在下面的代码中,我在fileNameMatches[0]上得到了标题错误linting。它不会忽略布尔检查。删除该支票不会修复或更改任何内容。有人知道如何解决这个问题吗

  protected getLocalFilename(): string {
    const fileNameMatches: string[]|null = this.filePath.match(/\/(.+\.js)$`/);
    if (Boolean(fileNameMatches) && fileNameMatches[0] !== null) { // TS2531: Object is possibly 'null'
      return fileNameMatches[0]; // TS2531: Object is possibly 'null'
    }
    else {
      throw Error("No filename found during regex matching")
    }
  }
也试过


此测试还返回可能为空的错误。

使用!要断言不为null的运算符:

 protected getLocalFilename(): string {
    const fileNameMatches: string[]|null = this.filePath.match(/\/(.+\.js)$`/);
    if (Boolean(fileNameMatches)) { 
      return fileNameMatches![0];
    }
    else {
      throw Error("No filename found during regex matching")
    }
  }
 protected getLocalFilename(): string {
    const fileNameMatches: string[]|null = this.filePath.match(/\/(.+\.js)$`/);
    if (Boolean(fileNameMatches)) { 
      return fileNameMatches![0];
    }
    else {
      throw Error("No filename found during regex matching")
    }
  }