javascript - Angular:类型“null”必须有一个返回迭代器的“[Symbol.iterator]()”方法
问题描述
我正在使用 Angular 7 和 TypeScript。我有一个函数,它可以获取像 ">10" 这样的字符串,并使用正则表达式从中提取运算符和数字。当我使用“ng build”编译它时,出现以下错误:
错误 TS2488:类型“null”必须具有返回迭代器的“Symbol.iterator”方法。
这是我的代码:
// Converts a string and number into an arithmetic expression and returns it.
private evaluate(value: number, rule: string) {
const [, operator, number ] = rule.match(/(\D+?)\s*(\d+)/);
// const [operator, number] = rule.match(/^(<|>|==)|.*$/g);
this.logger.debug(`Value: ${value}, Operator: ${operator}, Number: ${number}`);
switch (operator) {
case '>' : return value > Number(number);
case '<' : return value < Number(number);
case '==' : return value === Number(number);
}
return null;
}
我尝试更改我的 tsconfig 但没有任何效果。这是我当前的 tsconfig:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/lib",
"target": "es2015",
"module": "es2015",
"moduleResolution": "node",
"declaration": true,
"sourceMap": true,
"inlineSources": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"types": [],
"lib": [
"dom",
"es2018"
]
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"enableResourceInlining": true,
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
"strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
解决方案
我通过如下进行空检查来解决它:
private evaluate(value: number, rule: string) {
const matches: any = rule.match(/(\D+?)\s*(\d+)/);
if (matches === null) {
return null;
} else {
const operator = matches[1];
const number = matches[2];
this.logger.debug(`Value: ${value}, Operator: ${operator}, Number: ${number}`);
switch (operator) {
case '>' : return value > Number(number);
case '<' : return value < Number(number);
case '==' : return value === Number(number);
}
return null;
}
}
推荐阅读
- node.js - 在mongodb中搜索多个条件
- arrays - DeepCopy在for循环内的numpy数组的值
- javascript - 使用数组作为参数调用 JavaScript 构造函数
- java - 为什么 CentOs 6 上的 Glassfish 3.1 不能服务于端口 80?
- javascript - JS 无法与 AngularJS ng-view 一起正常工作
- php - 如何刷新共享首选项中的值?
- xml - 将工作表中一行的每 5 个值转置到另一个工作表中的列
- javascript - 在 redux-form 状态下保持 react-select 组件的值和标签
- python - 用精度值在python中计算两次之间的天数
- .net - Stylecop - 禁止类规则但不用于接口