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

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

    A new library called ts-optchain provides this functionality, and unlike lodash' solution, it also keeps your types safe, here is a sample of how it is used (taken from the readme):

    import { oc } from 'ts-optchain';
    
    interface I {
      a?: string;
      b?: {
        d?: string;
      };
      c?: Array<{
        u?: {
          v?: number;
        };
      }>;
      e?: {
        f?: string;
        g?: () => string;
      };
    }
    
    const x: I = {
      a: 'hello',
      b: {
        d: 'world',
      },
      c: [{ u: { v: -100 } }, { u: { v: 200 } }, {}, { u: { v: -300 } }],
    };
    
    // Here are a few examples of deep object traversal using (a) optional chaining vs
    // (b) logic expressions. Each of the following pairs are equivalent in
    // result. Note how the benefits of optional chaining accrue with
    // the depth and complexity of the traversal.
    
    oc(x).a(); // 'hello'
    x.a;
    
    oc(x).b.d(); // 'world'
    x.b && x.b.d;
    
    oc(x).c[0].u.v(); // -100
    x.c && x.c[0] && x.c[0].u && x.c[0].u.v;
    
    oc(x).c[100].u.v(); // undefined
    x.c && x.c[100] && x.c[100].u && x.c[100].u.v;
    
    oc(x).c[100].u.v(1234); // 1234
    (x.c && x.c[100] && x.c[100].u && x.c[100].u.v) || 1234;
    
    oc(x).e.f(); // undefined
    x.e && x.e.f;
    
    oc(x).e.f('optional default value'); // 'optional default value'
    (x.e && x.e.f) || 'optional default value';
    
    // NOTE: working with function value types can be risky. Additional run-time
    // checks to verify that object types are functions before invocation are advised!
    oc(x).e.g(() => 'Yo Yo')(); // 'Yo Yo'
    ((x.e && x.e.g) || (() => 'Yo Yo'))();
    

提交回复
热议问题