How keyof typeof Fixes TypeScript Object Indexing Errors
TypeScript throws an error when a plain string variable is used to index an object, because it cannot guarantee the string matches any of the object's keys. A developer encountered this issue while building a client invoice app, where a status prop typed as string failed to index a Tailwind CSS config object. The fix involves using the keyof typeof pattern, which extracts an object's keys as a union type, narrowing the accepted values to only valid keys. Applying keyof typeof statusConfig restricts the status prop to 'Paid', 'Pending', or 'Draft', resolving the type error. Unlike manually defined union types, this approach stays automatically in sync with the object, reducing maintenance overhead as keys are added or renamed.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in