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

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

    Another alternative that uses an external library is _.has() from Lodash.

    E.g.

    _.has(a, 'b.c')
    

    is equal to

    (a && a.b && a.b.c)
    

    EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.

提交回复
热议问题