javascript / expert
Snippet
Type-Safe Dependency Injection with Symbols
Using Symbols for Provide/Inject keys ensures that your dependency injection tokens are unique and cannot be overwritten by accidental string collisions in large-scale applications.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { provide, inject } from 'vue';// Define a unique key to avoid collisionsexport const ApiServiceKey = Symbol('ApiService');export const useApi = () => {const service = inject(ApiServiceKey);if (!service) throw new Error('ApiService not provided');return service;};export const provideApi = (instance) => provide(ApiServiceKey, instance);
vue
Breakdown
1
export const ApiServiceKey = Symbol('ApiService');
Creates a unique, immutable identifier that serves as a secure key for dependency injection.
2
const service = inject(ApiServiceKey);
Retrieves the provided dependency associated with the unique Symbol key.
3
if (!service) throw new Error(...);
Expert practice: Ensure the dependency exists to prevent runtime null pointer exceptions.