Search code examples
typescriptvue.jsopenapi-generatorvetur

Vue typescript error when filtering and mapping a list


I wonder what I need to do in order to remove the folloing error from my code:

I have these interface:

export interface ClassifierTO {

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

and:

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

They were auto generate by openapi-generator.

When I used this inside a method of class-component of vue:

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

Then the result inside the console of vs code is:

Object is possibly 'undefined'

What do I need to change that this will no longer be seen as an error? The typescript Version is 3.8.3 and this is 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"
  ]
}

Solution

  • This is because in your ClassifierTO interface, all the properties/keys are optional. intents?: Array<IntentTO>; tells TypeScript that the this.classifier.intents may return undefined.

    You can use the null coalescing operator to ensure that an array is returned all the time:

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

    Alternatively, simply update your interface such that intents is not an optional key.