javascript / expert
Snippet
Type-Safe Dependency Injection via Context Symbols
Using unique Symbols for Context keys avoids naming collisions in large projects. By wrapping getContext and setContext in typed functions, you create a robust dependency injection pattern that ensures type safety and provides helpful error messages during development.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const SERVICE_KEY = Symbol('auth-service');export function provideAuth(service: AuthService) {setContext(SERVICE_KEY, service);}export function useAuth() {const context = getContext<AuthService>(SERVICE_KEY);if (!context) throw new Error('AuthService not provided');return context;}
svelte
Breakdown
1
const SERVICE_KEY = Symbol(...);
Guarantees a unique key that cannot be accidentally overwritten.
2
setContext(SERVICE_KEY, service);
Provides the dependency to the component subtree.
3
if (!context) throw new Error(...);
Defensive programming to catch missing providers early.