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);
  • 相关阅读:
    月薪 30K Java 程序员,需要掌握哪些技术?
    docker-compose安装mongodb
    docker-compose安装apollo服务
    docker-compose安装mysql和redis
    编程总结1:打印沙漏
    秋季学习总结
    对我人生影响最大的三位老师
    自我介绍
    秋季学习总结
    人生路上对我影响最大的三位老师
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14714159.html
Copyright © 2011-2022 走看看