【发布时间】:2020-09-08 20:59:09
【问题描述】:
我见过 TypeScript 库,只需在类上添加注释,它就能够通过声明参数类型将这个类注入到其他类的构造函数中。
它是这样的:
@someAnnotation()
class Foo {
}
@someAnnotation()
class Bar {
}
@someAnnotation()
class A {
constructor(foo: Foo, bar: Bar) {
}
}
@someAnnotation()
class B {
constructor(a: A) {
}
}
然后神奇地,图书馆可以以某种方式获得这些
/// how do they get these?
const constructorArgumentsTypesOfA = [Foo, Bar]
const constructorArgumentsTypesOfB = [A]
这怎么可能?注释后面的代码是什么
这个库的一个例子是typedi
【问题讨论】:
-
所以
typedi的代码是公开可用的......为什么不看看呢? github.com/typestack/typedi/tree/develop/src/decorators -
那些被称为装饰器而不是注释。注释是一项被提议并随后从 ECMAScript 中废弃的功能。
标签: javascript typescript dependency-injection annotations static-typing