zoukankan      html  css  js  c++  java
  • [Typescript] Use the Optional Chaining Operator in TypeScript

    This lesson introduces the ?. operator which is known as optional chaining. We're going to look at how we can use ?. to safely descend into an object with properties which potentially hold the values null or undefined. We're also going to learn how to access properties with an expression using the ?.[] bracket notation and how to call functions which may not exist using the ?.() syntax.

    Chaining Operator for Function:

    type SerializationOptions = {
      formatting?: {
        getIndent?: () => number;
      };
    };
    
    function serializeJSON(value: any, options?: SerializationOptions) {
      const indent = options?.formatting?.getIndent?.();
      return JSON.stringify(value, null, indent);
    }
    
    const user = {
      name: "Marius Schulz",
      twitter: "mariusschulz",
    };
    
    const json = serializeJSON(user, {
      formatting: {
        getIndent: () => 2,
      },
    });
    
    console.log(json);

    For Array Syntax:

    type SerializationOptions = {
      formatting?: {
        "indent-level"?: number;
      };
    };
    
    function serializeJSON(value: any, options?: SerializationOptions) {
      const indent = options?.formatting?.["indent-level"];
      return JSON.stringify(value, null, indent);
    }
    
    const user = {
      name: "Marius Schulz",
      twitter: "mariusschulz",
    };
    
    const json = serializeJSON(user, {
      formatting: {
        "indent-level": 2,
      },
    });
    
    console.log(json);
  • 相关阅读:
    GeoServer与Spring MVC
    GeoServer二次开发1 hello Geoserver
    servlet的生命周期
    springboot打包出错,没有主清单
    空间数据库管理
    Gone with the wind
    谎言中的民众
    还是有些怀念这里啊
    MSN Protcol 学习笔记
    祝我的老师教师节快乐!
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14714159.html
Copyright © 2011-2022 走看看