Home > Software design >  How do you return an empty object in Typescript - or is there another way?
How do you return an empty object in Typescript - or is there another way?

Time:04-22

I'm learning Typescript (and React) and I'm trying to check if an object is null in order to skip further processing. I have a minimal example below.

If inputCat is null, I want to return right away to skip further processing, how do I do that in TypeScript?

  declare class Cat {
      color: string;
      // lots of more properties here
  }

  const processCat = (inputCat: Cat): Cat => {
      if(!inputCat) {
          return {};  // throws error: "Property 'color' is missing in type '{}' but required in type 'Cat'."
      }

      // lots of processing here
      return {
          ... inputCat,
          // lots of new variables here
      }
  }

When I try to return an empty object, TypeScript is complaining that:

Property 'color' is missing in type '{}' but required in type 'Cat'.

How do I return empty objects or null in Typescript? Or am I going about this the wrong way?

CodePudding user response:

Add null to return type (use union type Cat | null)

  const processCat = (inputCat: Cat): Cat | null => {
      if(!inputCat) {
          return null;
      }

      // lots of processing here
      return {
          ... inputCat,
          // lots of new variables here
      }
  }
  • Related