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