【发布时间】:2016-11-02 11:15:12
【问题描述】:
我正在尝试向 TypeScript 1.8.10 中的对象文字添加接口,但它似乎不起作用:
interface TestInterface {
value: string
}
let references = {
interfaceReference: TestInterface
}
如果我编译代码,编译器会抛出错误Cannot find name "TestInterface",尽管它之前已正确指定。作为 Angular 2 项目的一部分,我需要将接口添加到对象。
如果我用抽象类替换接口,一切似乎都可以工作:
abstract class TestInterface {
value: string
}
let references = {
interfaceReference: TestInterface
}
但是,能够在这些定义中使用接口会导致代码更简洁。所以,我希望有办法做到这一点。
编辑:澄清我想要做什么以及为什么我使用接口: Angular 2 包含依赖注入机制。您可以在引导代码的对象文字中指定从抽象服务定义到具体服务实现的映射:
bootstrap(AppComponent, [ { provide: TestInterface, useClass: TestClass} ]
但是,如果 TypeScript 无法将对象属性的值设置为接口,这将不起作用
【问题讨论】: