[英]Typescript get type constructor of each arguments of a constructor
我見過 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) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.