Angular · Senior · Question 21 of 75
Why use an abstract class as a DI token?
export abstract class Storage { abstract get(key: string): string | null; }
providers: [{ provide: Storage, useClass: LocalStorageService }]- ✓Correct answer: It defines a contract that exists at runtime, so implementations can be swapped per environment or in tests
- 2Abstract classes are created faster by the injector
- 3Interfaces work the same way, it is just a style preference
Explanation
Interfaces are erased at compile time and can't be tokens. An abstract class gives both a type and a runtime token, which is the Angular way to depend on abstractions.