Token<T> is a unique identifier used to register and retrieve dependencies from the container. It provides type-safe dependency resolution.
Import
Type Definition
- A symbol - For primitive types, configuration values, or when you want explicit naming
- A class constructor - The most common pattern, using the class itself as the token
- An object with prototype and name - For advanced use cases
Using Class Constructors as Tokens
The most common and recommended pattern is to use class constructors as tokens:Benefits of Class Tokens
- Type safety: TypeScript automatically infers the correct type
- No extra symbols: The class itself serves as both the type and the identifier
- Refactoring friendly: Renaming the class updates the token automatically
- IDE support: Better autocomplete and navigation
Using Symbols as Tokens
Use symbols for non-class dependencies like configuration values, primitives, or when you need explicit control:Symbol Token Best Practices
- Use descriptive names: Make the symbol description clear and meaningful
- Export from a central location: Keep token definitions organized
- Add type annotations: Specify the type when using
inject()
Type Safety
Tokens are generic and preserve type information:Choosing Between Class and Symbol Tokens
Use Class Tokens When:
- Registering services and business logic classes
- You want automatic type inference
- The dependency is represented by a class
- You prefer less boilerplate
Use Symbol Tokens When:
- Registering primitive values (strings, numbers, booleans)
- Registering configuration objects
- You need multiple providers of the same type
- You want to decouple the token from the implementation