【问题标题】:Vue typescript error when filtering and mapping a list过滤和映射列表时出现Vue typescript错误
【发布时间】:2020-08-14 19:03:45
【问题描述】:

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

我有这些界面:

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代码控制台里面的结果是:

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

【问题讨论】:

    标签: typescript vue.js openapi-generator vetur


    【解决方案1】:

    定义中的问号告诉 typescript 这是可选的,可以为空。

    export interface ClassifierTO {
    
       id?: number;
       classifierName?: string;
       userId?: number;
       intents?: Array<IntentTO>;
    }
    

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

    【讨论】:

      【解决方案2】:

      这是因为在您的ClassifierTO 界面中,所有属性/键都是可选的。 intents?: Array&lt;IntentTO&gt;; 告诉 TypeScript this.classifier.intents 可能返回 undefined。

      您可以使用 null 合并运算符来确保始终返回一个数组:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-04
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多