Why is it possible to provide an injection token of some type but can pass an actual value of a differing type and this be accepted in a service injected with the token?
import { InjectionToken } from '@angular/core';
export const CONFIG = new InjectionToken<string>("SomeToken");
export interface Config {
environment: 'someEnv' | 'someEnvTwo';
}
export function configurationFactory(): any {
const configuration = {
environment: 'someEnv';
}
return configuration;
}
@NgModule({
imports: [...],
exports: [...],
providers: [
{
provide: CONFIG,
useFactory: configurationFactory
}
]
})
export class SomeModule { }
@Injectable({
providedIn: 'root',
})
export class ConfigurationService {
constructor(@Inject(CONFIG) private config: Config) {
const environment = config.environment;
}
}
In this case, the ConfigurationService is injected with the CONFIG
token that is of type string
but defines the type as Config
. In the module it specifies providing the CONFIG
token and using a value typed as any
but conforms to the Config
interface.
Wouldn't the ConfigurationService have a conflict with the token, being specified as type string
, not conforming to the Config
type in the construction parameter?
Wouldn't the module's provided CONFIG_TOKEN
conflict with the factory returning an any
object rather than a string
?
Referencing the Angular DI Documentation suggests to me that this shouldn't be possible, however this does work.