Home > Mobile >  Typescript: Object is possibly 'undefined' for an object with different types of children
Typescript: Object is possibly 'undefined' for an object with different types of children

Time:09-29

I have an object that can have 2 types of children

type data = {
  name: Names[];
}
type Names = {
    name?: string;
    names?: string[];
};

I am writing an adapter to configure the response data according to schema

const name = data[dataLength - 1].hasOwnProperty('name') ? data[dataLength - 1].name : data[dataLength - 1].names[0]
      

data[dataLength - 1].names[0] is the place where I am getting Object is possibly 'undefined'.ts(2532)

How can I resolve this?

CodePudding user response:

If you are 100% sure that names will not be undefined in this point of the code, you could use the following syntax to let Typescript know you are sure that names is not undefined

const name = data[dataLength - 1].hasOwnProperty('name') ? data[dataLength - 1].name : data[dataLength - 1].names![0]

Notice the ! at the very end.

USE WITH CARE! Otherwise expand your code to do more checks to let the compiler narrow down the type better or rewrite some types to have less optional properties.

  • Related