Skip to Content
GuidesIdentifier

Identifier

An identifier is a unique token used to look up a dependency from the injector.

Using a Class as Identifier

The simplest approach is to use the class itself as the identifier:

class AuthService {} const injector = new Injector([[AuthService]]); const auth = injector.get(AuthService);

This is convenient but couples your code to the concrete implementation.

For better abstraction, use createIdentifier to create an identifier for an interface:

// 1. Define the interface and create an identifier interface IClipboardService { readText(): string | undefined; } const IClipboardService = createIdentifier<IClipboardService>("clipboard");

In TypeScript, type names and value names are in different namespaces. This allows us to use the same name IClipboardService for both the interface and the identifier.

// 2. Create different implementations class WebClipboardService implements IClipboardService { readText() { return navigator.clipboard.readText(); } } class MobileClipboardService implements IClipboardService { readText() { return bridge.readText(); } } // 3. Inject different implementations based on environment const injector = new Injector([ [IClipboardService, { useClass: WebClipboardService }], // for web // or [IClipboardService, { useClass: MobileClipboardService }], // for mobile ]); // 4. Get the dependency - same code works in both environments const clipboard = injector.get(IClipboardService);

Benefits of Using Identifiers

BenefitDescription
Loose couplingYour code depends on interfaces, not implementations
Easy testingSwap real services with mocks easily
FlexibilitySwitch implementations without changing consumer code
Last updated on