Menu

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

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

DEV Community: typescript·郭帅·8 days ago
#uK5AMN2h
#devtotypescript#devto#dev#string#label
Reading 0:00
15s threshold

郭帅 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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.