简体   繁体   中英

Why assigning to property resulting error “cannot set property of null”

I am trying to assign some value to some property of object. But the console logged error ERROR TypeError: Cannot set property 'requested_date' of null . I have tried to find what is wrong but I think it's all fine.

Here is the code:

form = {
    data: null as IMediaStorageAdd,
    requester: null as string
}

The IMediaStorageAdd is an interface:

export interface IMediaStorageAdd {
    place: string;
    requested_date: any;
    temp_requested_date: any;
    details: any[];
}

and this is where i run the assignemnt:

ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    this.form.data.requested_date = new Date();
    /* resulting error Cannot set property 'requested_date' of null */
}

Before setting the requested date, you need assign an empty object to data property of the form. Otherwise data is null and hence it is throwing the error. To fix it,

add a line before setting the requested_date as,

this.form.data = {};

The answer of Sajeetharan is correct and it's working. I will try to shed some lights to clarify your doubts.

You are setting this.form.data to null and typecasting it using an interface, but still this.form.data is null and not an object.

I believe you can compile TS with --strictNullChecks to avoid this confusion in order to avoid assigning null or undefined to anything.

Anyway, in your case, I think either you initialise your form using same types as you expect:

form = {
    data: {} as IMediaStorageAdd,
    requester: '' as string
}

or you need to initialise your form data before use it:

1) If there's a class implemeting your IMediaStorageAdd interface

ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    // where class MediaStorageAdd implements IMediaStorageAdd
    this.form.data = new MediaStorageAdd();
    // this could be done in the class MediaStorageAdd constructor actually
    this.form.data.requested_date = new Date();
}

2) If no class is implementing your IMediaStorageAdd interface, then you should define it as a type, first of all and then initialise your form data using an object literal

export type TMediaStorageAdd {
    requested_date: any;
    place?: string;
    temp_requested_date?: any;
    details?: any[];
}

form = {
    data: null as TMediaStorageAdd,
    requester: null as string
}

ngOnInit() {
    this.form.requester = localStorage.getItem(`name`);
    this.form.data = {
        requested_date = new Date();
    }
}

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