Safe navigation operator (?.) or (!.) and null property paths

前端 未结 6 1163
清歌不尽
清歌不尽 2020-11-27 14:32

In Angular 2 templates safe operator ?. works, but not in component.ts using TypeScript 2.0. Also, safe navigation operator (!.) doesn

6条回答
  •  野性不改
    2020-11-27 15:26

    Update:

    Planned in the scope of 3.7 release
    https://github.com/microsoft/TypeScript/issues/33352


    You can try to write a custom function like that.

    The main advantage of the approach is a type-checking and partial intellisense.

    export function nullSafe
        (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
        let result: any = obj;
    
        const keysCount = arguments.length - 1;
        for (var i = 1; i <= keysCount; i++) {
            if (result === null || result === undefined) return result;
            result = result[arguments[i]];
        }
    
        return result;
    }
    

    And usage (supports up to 5 parameters and can be extended):

    nullSafe(a, 'b', 'c');
    

    Example on playground.

提交回复
热议问题