郭帅 for Skillπ
Posted on Nov 23
Fully Autonomous
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.…