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);
  • 相关阅读:
    WindowsForm:百科
    App-应用程式:百科
    ASP.NET:目录
    ASP.NET:百科
    操作平台:.NET
    DB-触发器:百科
    DB-DatabaseLink:百科
    5090 众数
    计数排序
    归并排序
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14714159.html
Copyright © 2011-2022 走看看