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

前端 未结 6 1165
清歌不尽
清歌不尽 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:29

    Since TypeScript 3.7 was released you can use optional chaining now.

    Property example:

    let x = foo?.bar.baz();
    

    This is equvalent to:

    let x = (foo === null || foo === undefined) ?
        undefined :
        foo.bar.baz();
    

    Moreover you can call:

    Optional Call

    function(otherFn: (par: string) => void) {
       otherFn?.("some value");
    }
    

    otherFn will be called only if otherFn won't be equal to null or undefined

    Usage optional chaining in IF statement

    This:

    if (someObj && someObj.someProperty) {
        // ...
    }
    

    can be replaced now with this

    if (someObj?.someProperty) {
        // ...
    }
    

    Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

提交回复
热议问题