Vue · Middle · Question 15 of 75
Why use an InjectionKey symbol instead of a string for provide/inject?
export const ThemeKey: InjectionKey<Ref<string>> = Symbol("theme");
provide(ThemeKey, theme);
const t = inject(ThemeKey); // Ref<string> | undefined- ✓Correct answer: Symbols avoid name collisions and carry the type, so
injectis typed - 2Strings are not allowed as keys
- 3Symbols make injection faster
Explanation
Put keys in a shared file. inject returns T | undefined unless you pass a default value.