[Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)
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 null, undefined, false, "", 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);

浙公网安备 33010602011771号