typescript Angular 2 OpaqueToken 与 Angular 4 InjectionToken
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43419050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 OpaqueToken vs Angular 4 InjectionToken
提问by Estus Flask
InjectionToken
was introduced in Angular 4 and OpaqueToken
was marked as deprecated.
InjectionToken
在 Angular 4 中引入OpaqueToken
并被标记为已弃用。
According to the manual, it is supposed to be used as
根据手册,它应该用作
const anyToken = new InjectionToken('any');
for untyped token, and as
对于无类型标记,以及
const numberToken = new InjectionToken<number>('number');
for typed token.
用于键入令牌。
However, typed token still can be injected and used with different type when it is injected, TypeScript will be ok with this, won't it?
但是,typed token 仍然可以注入并在注入时与不同的类型一起使用,TypeScript 可以解决这个问题,不是吗?
constructor(@Inject(numberToken) any, @Inject(numberToken) string: string) { ... }
How is InjectionToken
supposed to benefit from TypeScript type system?
InjectionToken
应该如何从 TypeScript 类型系统中受益?
Why was OpaqueToken
deprecated if there's no practical difference between those two?
OpaqueToken
如果这两者之间没有实际区别,为什么会被弃用?
回答by Max Koretskyi
Based on the internal usage of InjectionToken
, for example, here, I assume that InjectionToken
gives you type checking benefit when getting a dependency through injector
instance:
InjectionToken
例如,基于 的内部用法,这里,我假设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'.
}
}