javascript / expert
Snippet
Type-Safe Dependency Injection with InjectionKey
Using Symbols with InjectionKey ensures that your provide/inject architecture is both unique and type-safe. This prevents key collisions in large-scale applications and allows TypeScript to infer the exact shape of the injected dependency, removing the need for manual casting.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { provide, inject, InjectionKey } from 'vue';interface AuthService {login: () => Promise<void>;user: string;}export const AuthKey: InjectionKey<AuthService> = Symbol('AuthService');// Providerprovide(AuthKey, {user: 'Admin',login: async () => {}});// Consumerconst auth = inject(AuthKey);if (!auth) throw new Error('AuthService not provided');
vue
Breakdown
1
export const AuthKey: InjectionKey<AuthService> = Symbol('AuthService');
Creates a unique Symbol key linked to a specific TypeScript interface.
2
provide(AuthKey, { ... });
Registers the dependency in the component hierarchy using the typed key.
3
const auth = inject(AuthKey);
Retrieves the dependency with full TypeScript autocomplete and type checking.