首页 > 其他 > 详细

[Typescript] Use the Optional Chaining Operator in TypeScript

时间:2021-04-28 16:29:34      阅读:20      评论:0      收藏:0      [点我收藏+]

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);

 

[Typescript] Use the Optional Chaining Operator in TypeScript

原文:https://www.cnblogs.com/Answer1215/p/14714159.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!