InjectionToken是在Angular 4中引入的,而OpaqueToken被标记为不推荐使用。
According to the manual,它应该被用作
const anyToken = new InjectionToken('any');用于非类型化的令牌,以及as
const numberToken = new InjectionToken<number>('number');用于键入的令牌。
但是,类型化的token在注入时仍然可以注入和使用不同的类型,TypeScript可以接受这一点,不是吗?
constructor(@Inject(numberToken) any, @Inject(numberToken) string: string) { ... }InjectionToken如何从TypeScript类型系统中获益?
如果这两者之间没有实际区别,为什么OpaqueToken会被弃用?
发布于 2017-04-16 13:48:26
基于InjectionToken的内部使用,例如here,我假设InjectionToken在通过injector实例获取依赖项时为您提供了类型检查的好处:
import {Component, InjectionToken, Injector} from "@angular/core";
interface AppConfig {
name: string;
}
let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
let appConfig: AppConfig = {name: 'Cfg'};
@Component({
...
providers: [{provide: APP_CONFIG, useValue: appConfig}]
})
export class TestComponent {
constructor(injector: Injector) {
const config = injector.get(APP_CONFIG);
config.s = 'd';
^^^^^ - Error:(14, 16) TS2339:Property 's' does not exist on type 'AppConfig'.
}
}https://stackoverflow.com/questions/43419050
复制相似问题