javascript / expert
Snippet
Strict InjectionKey Symbol Contracts for Hierarchical State Provision
This snippet shows how JavaScript Symbols and TypeScript InjectionKey interfaces establish runtime and compile-time type safety across Vue dependency injection trees. Using typed InjectionKey tokens guarantees unique key collision prevention while validating injected context availability.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { provide, inject, InjectionKey, ref, Ref } from 'vue';interface UserContext {userId: Ref<string>;permissions: Ref<string[]>;revokeAccess: () => void;}export const USER_CONTEXT_KEY: InjectionKey<UserContext> = Symbol('UserContextKey');export function useProvideUserContext(id: string) { const userId = ref(id);const permissions = ref(['read', 'write']);const revokeAccess = () => { permissions.value = []; };const context: UserContext = { userId, permissions, revokeAccess };provide(USER_CONTEXT_KEY, context);return context;}export function useInjectUserContext(): UserContext {const context = inject(USER_CONTEXT_KEY);if (!context) {throw new Error('UserContext injection attempted outside provider subtree');}return context;};
vue
Breakdown
1
export const USER_CONTEXT_KEY: InjectionKey<UserContext> = Symbol('UserContextKey');
Creates a unique Symbol token typed with Vue's InjectionKey interface to prevent runtime lookup collisions.
2
const context: UserContext = { userId, permissions, revokeAccess };
Constructs a typed contract payload bundling reactive ref state and mutator methods.
3
provide(USER_CONTEXT_KEY, context);
Binds the strongly-typed contextual state to the component tree under the unique Symbol key.
4
const context = inject(USER_CONTEXT_KEY);
Retrieves provided dependencies up the component hierarchy using the Symbol identifier.
5
if (!context) { throw new Error(...); }
Enforces runtime assertion guarantees when accessing context outside valid provider subtrees.