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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:27:09  来源:igfitidea点击:

Angular 2 OpaqueToken vs Angular 4 InjectionToken

angulartypescript

提问by Estus Flask

InjectionTokenwas introduced in Angular 4 and OpaqueTokenwas 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 InjectionTokensupposed to benefit from TypeScript type system?

InjectionToken应该如何从 TypeScript 类型系统中受益?

Why was OpaqueTokendeprecated 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 InjectionTokengives you type checking benefit when getting a dependency through injectorinstance:

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'.
    }
}