Typescript获取构造函数的每个参数的类型构造函数



我见过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的代码,我发现它们使用了一个名为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) {
}
}

最新更新