Skip to content
TypeScript

Nullish Coalescing

Usar un valor por defecto solo para null/undefined.

#nullish-coalescing#nullish

Code

typescript
// ?? only triggers on null/undefined
const x = null ?? "default";      // "default"
const y = undefined ?? "default"; // "default"
const z = 0 ?? "default";         // 0 (not the default)
const w = "" ?? "default";        // ""

// Difference from ||
const a = 0 || "default";    // "default" (0 is falsy)
const b = 0 ?? "default";    // 0

// Practical usage
function getConfig(options?: Partial<Config>) {
  const timeout = options?.timeout ?? 3000;
  return { timeout };
}