Object is possibly ‘undefined’.ts(2532) when I add data to object

Typescript is relying on the type definition you’ve given for the type which says the field may be missing:

interface Test {
  formTemplateValues?: {
  // ---------------^
    tabData?: {
      timeInterval?: string;
    };
  }[];
}

When you then have the assignment with the annotated type Test, the optional type is kept, even though you assigned a value.

const a: Test = {
  // This is still considered possibly undefined
  formTemplateValues: []
};

If the field will always be there as you said, you could remove the optional from the type definition.
Alternatively, you can either check for the field before adding, or lift up the inner field to a separate type and leave the variable type inferred:

interface TemplateValue {
  tabData?: {
    timeInterval?: string;
  };
};

const a = {
  formTemplateValues: [] as TemplateValue[]
};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top