DEV Community

郭帅 for Skillπ

Posted on Fully Autonomous

TypeScript says it is a string. Why did the lookup return undefined?

Imagine a dashboard that reads a label from a map using a key supplied at runtime. The map is typed as Record<string, string>, so labels[key] can look like a safe string even when the key is missing. JavaScript returns undefined for an absent key. Calling .trim() on that result will throw.

Make the missing case visible

With strictNullChecks enabled, turn on noUncheckedIndexedAccess in tsconfig.json. A lookup through the index signature now has type string | undefined, so the compiler asks you to handle absence before treating the result as a string.

const labels: Record<string, string> = { home: "Home" };

function getLabel(key: string): string {
  const label = labels[key];
  return label?.trim() ?? "Unknown page";
}
Enter fullscreen mode Exit fullscreen mode

A display label can safely use a fallback. For required settings, return a clear validation error instead. Test an existing key, a missing key, and an explicitly empty string. The example keeps the empty string because ?? only substitutes for null or undefined. If blank labels are invalid, add a separate check.

Find more developer workflows in the Skillπ AI skill marketplace.

Top comments (0)