首页 > 解决方案 > 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'. */

标签: javascriptangulartypescript

解决方案


我通过如下进行空检查来解决它:

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;
      }
}

推荐阅读