今日已更新 327 条资讯 | 累计 29089 条内容
关于我们

Typing Vue 3 provide/inject Without Losing Autocomplete

Faisal Nadeem 2026年08月07日 02:17 0 次阅读 来源:Dev.to

Strict prop types and typed emits get most of the attention in Vue 3 + TypeScript setups, but provide / inject is where type safety quietly falls apart if you use the API the way the docs show it by default. inject() without a type hint returns unknown , which means every consumer of an injected value either casts it blindly or loses autocomplete entirely — and a typo in the injection key becomes a runtime undefined instead of a compile-time error. The Default Setup Is Untyped by Construction The naive version compiles, but gives you nothing: // Provider provide ( ' theme ' , currentTheme ); // Consumer const theme = inject ( ' theme ' ); // type: unknown Nothing here catches a typo in the key string, and nothing tells the consumer what shape theme actually has. Both problems come from using a plain string as the injection key. InjectionKey Fixes Both Problems at Once Vue exports an InjectionKey<T> type specifically for this. Define it once, typed, and both provide and inject become fully type-checked against the same symbol: // keys.ts import type { InjectionKey } from ' vue ' ; export interface Theme { mode : ' light ' | ' dark ' ; accentColor : string ; } export const ThemeKey : InjectionKey < Theme > = Symbol ( ' theme ' ); // Provider import { ThemeKey } from ' ./keys ' ; provide ( ThemeKey , { mode : ' dark ' , accentColor : ' #4f46e5 ' }); // Consumer import { ThemeKey } from ' ./keys ' ; const theme = inject ( ThemeKey ); // type: Theme | undefined The | undefined in that last type isn't a quirk — it's inject being honest that a consumer might render without a matching provider above it in the tree, which is a real runtime possibility TypeScript is right to force you to handle. Handling the undefined Case Without Littering ?. Everywhere The common mistake is providing a default value to silence the undefined type instead of actually checking for it: const theme = inject ( ThemeKey , { mode : ' light ' , accentColor : ' #000 ' }); // default masks missing pro

本文内容来源于互联网,版权归原作者所有
查看原文