过滤和映射列表时出现 Vue 打字稿错误

Vue typescript error when filtering and mapping a list

我想知道我需要做什么才能从我的代码中删除以下错误:

我有这些界面:

export interface ClassifierTO {

   id?: number;
   classifierName?: string;
   userId?: number;
   intents?: Array<IntentTO>;
}

和:

export interface IntentTO {
   id?: number;
   intentName?: string;
   classifierId?: number;
   numberOfSamples?: number;
}

它们是由 openapi-generator 自动生成的。

当我在 vue 的 class-component 方法中使用它时:

 let intents = this.classifier.intents
        .filter(intent => intent.intentName === "test")
        .map(intent => intent.numberOfSamples);

那么vs code的控制台里面的结果是:

Object is possibly 'undefined'

我需要更改什么才能不再将其视为错误? 打字稿版本是 3.8.3 这是 tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

您定义中的问号告诉打字稿这是可选的,可以为空。

export interface ClassifierTO {

   id?: number;
   classifierName?: string;
   userId?: number;
   intents?: Array<IntentTO>;
}

您可以删除问号或只检查是否设置了意图。

这是因为在你的ClassifierTO界面中,所有的properties/keys都是可选的。 intents?: Array<IntentTO>; 告诉 TypeScript this.classifier.intents 可能 return 未定义。

您可以使用 null 合并运算符来确保数组始终处于 returned:

let intents = (classifier.intents ?? [])
    .filter(intent => intent.intentName === "test")
    .map(intent => intent.numberOfSamples);

或者,只需更新您的界面,使 intents 不是可选键。