angulartypescriptangularjs-directive

Angular Save Navigation Operator not working as expected


I'm running into an issue where the Safe Navigation Operator (?) is not working as intended.

task = {
    title: 'Review applications',
    assignee: null
};
test = this.task.assignee?.name;

enter image description here

Produces the following error:

TS2339: Property 'name' does not exist on type 'never'.

Current Environment

I had done a search and found a similar issue, but it revolves around using an older version of typescript, of which I am using a newer version, and would think this issue would not exist at this time:

Additional information on how Safe Navigation Operators should work can be found here:

Line 26:   nullItem = null;
Line 52: <p>The null item's name is: {{nullItem?.name}}</p>

enter image description here

How can I solve this issue?


Solution

  • Try defining the interface highlighting to typescript that value can be present or can be null! Else it will infer the type of assignee is null based on the value and this is giving you the error!

    export interface Task {
        title: string;
        assignee: {name:string} | null;
    }
    
    task: Task = {
        title: 'Review applications',
        assignee: null
    };
    test = this.task.assignee?.name;