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);
  • 相关阅读:
    Linux下安装Mysql
    mssql 查询效率
    查看apache是否安装及版本
    centos(linux)切换用户
    mysql操作命令(linux)
    远程连接MySql连不上1130
    JAVA环境配置
    SQLSERVER2012数据库还原
    ASP连接ACCESS数据库
    ODOO 常用widget
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14714159.html
Copyright © 2011-2022 走看看