我见过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
发布于 2020-09-09 05:25:10
通过查看typedi的代码,我发现它们使用了一个名为reflect-metadata的库
这项工作是这样完成的
const paramTypes = Reflect.getMetadata('design:paramtypes', A);
console.log(paramTypes)更具体地说,必须在调用import 'reflect-metadata'之前调用它。
此外,装饰器也是必需的。但是任何函数都可以工作,甚至是一个空的函数装饰器。
function Service(target: any) {
}像这样使用
@Service
class A {
id = 'A'
constructor(foo: Foo, bar: Bar) {
}
}https://stackoverflow.com/questions/63801492
复制相似问题