Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get rid of "Object is possibly 'undefined'" error without using non-null assertion or optional chaining

I have the code like below

export type ConditionalItemType = [
  { condition: string },
  { [key: string]: FormItemDataType }
];
export type ConditionalItemDataType = ConditionalItemType[];

export type FormItemDataType = {
  required: boolean;
  type: string;
  constraint?: TextConstraintType;
  options?: string[];
  conditional?: ConditionalItemDataType;
};

export type TextConstraintType = {
  min?: number;
  max?: number;
  format?: string;
};

const obj: FormItemDataType = {
  required: true,
  type: 'select',
  options: ['simple', 'complicated'],
  conditional: [
    [
      { condition: 'complicated' },
      {
        'How Complicated': {
          required: true,
          type: 'text',
          constraint: {
            max: 30,
          },
        },
      },
    ],
  ],
};

const func = (input: FormItemDataType) => {
  if ('conditional' in input) {
    input.conditional.filter((arrItem) => console.log(arrItem));
  } else null;
};

I am getting 'input.conditional' is possibly 'undefined' error at input.conditional.filter((arrItem) => console.log(arrItem)).

How to get rid of this error? I cannot use non-null assertion or optional chaining . I cannot change the type either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I thought I could do this by using "Type Guards" & I assume I am doing that at if ('conditional' in input) but apparently not. Can anyone help?

Update
enter image description here

>Solution :

Ditch the in operator and just check if the input.conditional is set, the classic way.

const func = (input: FormItemDataType) => {
  if(input.conditional) { // 👈 tells TypeScript that input.conditional under this block must be set
    input.conditional.filter((arrItem) => console.log(arrItem));
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading