This lesson introduces the ?? operator which is known as nullish coalescing. The ?? operator produces the value on the right-hand side if (and only if) the value on the left-hand side is null or undefined, making it a useful operator for providing fallback values.

We'll contrast the ?? operator with the || logical OR operator which produces the value on the right-hand side if the value on the left-hand side is any falsy value (such as nullundefinedfalse""0, …).

If you want to provide default value, use ?? instead of ||

type SerializationOptions = {
  formatting?: {
    indent?: number;
  };
};

function serializeJSON(value: any, options?: SerializationOptions) {
  const indent = options?.formatting?.indent ?? 2;
  return JSON.stringify(value, null, indent);
}

const user = {
  name: "Marius Schulz",
  twitter: "mariusschulz",
};

const json = serializeJSON(user, {
  formatting: {
    indent: 0,
  },
});

console.log(json);

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2021-07-24
猜你喜欢
  • 2021-11-07
  • 2021-11-24
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
相关资源
相似解决方案