首页 > 解决方案 > TS2531:在 .match() 期间对象可能为“空”

问题描述

在下面的代码中,我得到标题错误 linting on fileNameMatches[0]。它不会在Boolean()支票上掉毛。删除该检查不会修复或更改任何内容。有谁知道如何解决这一问题?

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")
  }
}

也试过

if (typeOf fileNameMatches !== "null") {

此测试也返回"Object is possibly 'null'"错误。

标签: typescript

解决方案


修复了使用!运算符断言 not null on fileNameMatches![0]

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")
  }
}

推荐阅读