zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)

typescript in The use Operator
2023-09-14 09:00:46 时间

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