DEV Community

JW SOLUTIONS
JW SOLUTIONS

Posted on Originally published at jw-solutions.com

Modern TypeScript: ?., ?? and satisfies without formatting errors

Tip of the week

Three operators cut defensive code: optional chaining ?., nullish coalescing ?? and TypeScript 4.9+'s satisfies operator, which checks the type without widening the value.

const config = {
  retries: 3,
  endpoint: "https://api.example.com",
} satisfies Record<string, string | number>;

const timeout = options?.timeout ?? 5000;
const city = user?.address?.city ?? "Sin ciudad";
Enter fullscreen mode Exit fullscreen mode

Quick rules

  • Use ?? (not ||) when 0 or "" are valid values.
  • Avoid ?. chains longer than three levels: a sign of a poorly designed model.
  • Prefer satisfies over as so type errors are not silenced.

Try it interactively: Format, validate, and auto-document your javascript directly in JW Solutions Code Formatter & Auto-Doc AI.
Originally published at jw-solutions.com.

Top comments (0)