How to Fix Type Safety Gaps in Vue 3 provide/inject with InjectionKey
Vue 3's provide/inject API loses type safety when plain strings are used as injection keys, causing inject() to return unknown and leaving typos undetected until runtime. Vue's built-in InjectionKey type, combined with a shared Symbol, allows both provide and inject to be fully type-checked against the same interface. The undefined in the inferred type is intentional, signaling that a component may render without a matching provider in the tree — a real runtime risk that should be handled explicitly rather than silenced with a default value. Wrapping inject calls in a dedicated composable, such as useTheme(), centralizes the null check, error message, and type narrowing in one place instead of repeating them across every consumer. When providing reactive values like refs, the InjectionKey generic must reflect the wrapped type to avoid confusing errors around .value access.
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