Angular Error error TS2532: Object is possibly 'undefined'

Al *_*ant 1 java spring jhipster angular

I have been unable to find why I am getting this error on a Angular project.

Plan contains and array of Tasks. Each Task contains an entity called MetaTime. MetaTime has a field TaskStart.

plan.usergen.model.ts

import { Moment } from 'moment';
import {ITaskUsergen} from "app/shared/model/task.usergen.model";

export interface IPlan {
  id?: number;
  name?: string;
  startDate?: Moment;
  tasks?: ITaskUsergen[];
}

export class Plan implements IPlan {
  constructor(
    public id?: number,
    public name?: string,
    public startDate?: Moment,
    public tasks?: ITaskUsergen[],
  ) {}
}
Run Code Online (Sandbox Code Playgroud)

task.usergen.model.ts

import {ITask, Task} from "app/shared/model/task.model";
import {MetaTime} from "app/shared/model/meta-time.model";

export interface ITaskUsergen extends ITask {
  metaTime?: MetaTime;
}

export class TaskUserGen extends Task implements ITaskUsergen {
  constructor(public metaTime?: MetaTime) {
    super();
  }
}
Run Code Online (Sandbox Code Playgroud)

meta-time.model.ts

import { Moment } from 'moment';

export interface IMetaTime {
  id?: number;
  taskStart?: Moment;
  taskDuration?: number;
  taskInterval?: number;
  taskRepeat?: number;
}

export class MetaTime implements IMetaTime {
  constructor(
    public id?: number,
    public taskStart?: Moment,
    public taskDuration?: number,
    public taskInterval?: number,
    public taskRepeat?: number
  ) {}
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

The full error is:

ERROR in src/main/webapp/app/entities/plan-usergen/plan-detail.component.html:47:46 - error TS2532: Object is possibly 'undefined'.
47   <td>{{ task.metaTime.taskStart }}</td>
                                            ~~~~~~~~
src/main/webapp/app/entities/plan-usergen/plan-detail.component.ts:7:16
7   templateUrl: './plan-detail.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component PlanDetailComponent.
Run Code Online (Sandbox Code Playgroud)

321*_*21X 8

It's probably because you're compiling AOT (Ahead of Time) and the metaTime is nullable (the questionmark after metaTime?).

The compiler gives the error because it's pretty strict I think (not quite an angular expert myself) but you should do a null-check to prevent the possible null situation.

You can at least fix it by using this, the question is whether this is the behavior YOU expect to happen:

<td>{{ task.metaTime?.taskStart }}</td>
Run Code Online (Sandbox Code Playgroud)

In the end it's all about having code that behaves like you would expect.