简体   繁体   中英

Object is possibly 'undefined' after validation in TypeScript

Please see the following code. Do we have a convenient method to overcome this?

interface IAnimal {
  type?: "animal" | "bird";
  body?: {
    legs?: number;
  };
}

// validate type and body.legs exists
function validator(animal:IAnimal){
  if(!animal || !animal.body|| !animal.body.legs){
    throw new Error('invalid');
  }
  console.log(animal.body.legs); // fine here
}

function foo(animal:IAnimal){
  validator(animal); // we called validation here

  console.log(animal.body.legs);
  //          ^^^^^^^^^^^ =========> Error: Object is possibly 'undefined'.ts(2532)
}

I know this can be solved by the ..

console.log(animal.body!.legs); // fine

But if this is a large function, we need to use this .. throughout the entire function even after the proper validation, which doesn't look good. This error prone also. Is there any convenient way to overcome this?

Your interface IAnimal , sets body is nullable , the issue not come from your validator function. If body and legs are required, set these are required.

interface IAnimal {
  type?: "animal" | "bird";
  body: { // remove nullable mark
    legs: number; // ...
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM