Intermediate LevelVue JS
Why should you use TypeScript InjectionKey Symbols with provide and inject?
❓ Interview Prompt: Explain provide/inject string collision risks, TypeScript InjectionKey<T> symbols, and type-safe dependency injection.
Using plain string keys ('provide("user", userData)') for dependency injection across large team codebases introduces two problems:
1
String Collisions: Two different team modules might use the string '"user"', overwriting each other's context.
2
Missing Type Safety: 'inject("user")' returns type 'unknown' by default.
Solution - 'InjectionKey<T>' Symbols:
Define unique JavaScript Symbols typed with Vue's 'InjectionKey<T>' interface. This guarantees unique keys and gives full TypeScript type inference when calling 'inject(key)'!
Code Implementation Example
typescript
// keys.ts
import { InjectionKey, Ref } from 'vue';
export interface UserStore {
username: Ref<string>;
logout: () => void;
}
// 1. Create unique typed Symbol InjectionKey
export const UserKey: InjectionKey<UserStore> = Symbol('UserStore');
// In Parent Component:
// provide(UserKey, { username, logout });
// In Child Component:
// const userStore = inject(UserKey); // Fully typed as UserStore!💡Type-safe dependency injection using TypeScript InjectionKey Symbols.
🎯 Interview Key Takeaway
Use InjectionKey<T> Symbols with provide/inject to eliminate string collisions and enforce TypeScript type safety.
#InjectionKey#provide#inject#TypeScript#Intermediate
Back to all Vue JS Questions→