简体   繁体   English

打字稿获取构造函数的每个参数的类型构造函数

[英]Typescript get type constructor of each arguments of a constructor

I have seen TypeScript libraries that by just add an annotation on the class, it is capable of injecting this class into the constructor of other class by just declaring the argument type.我见过 TypeScript 库,只需在类上添加注释,它就能够通过声明参数类型将此类注入到其他类的构造函数中。

It goes something like this:它是这样的:

@someAnnotation()
class Foo {
}

@someAnnotation()
class Bar {
}

@someAnnotation()
class A {
    constructor(foo: Foo, bar: Bar) {
    }
}

@someAnnotation()
class B {
    constructor(a: A) {
    }
}

Then magically, the libary can somehow get these然后神奇的是,图书馆可以以某种方式获得这些

/// how do they get these? 
const constructorArgumentsTypesOfA = [Foo, Bar]
const constructorArgumentsTypesOfB = [A]

How is this possible ?这怎么可能 ? What is the code behind the annotation注释背后的代码是什么

An example of this library is typedi这个库的一个例子是typedi

By looking at the code of typedi, I found that they use a library called reflect-metadata通过查看typedi的代码,发现他们使用了一个叫做reflect-metadata的库

And the job is done like this工作是这样完成的

const paramTypes = Reflect.getMetadata('design:paramtypes', A);
console.log(paramTypes)

To be more specific, import 'reflect-metadata' must be called before anything else.更具体地说,必须先调用import 'reflect-metadata'

Also, the decorator is required.此外,还需要装饰器。 But any would work, even an empty function decorator但是任何都可以工作,即使是一个空的函数装饰器

function Service(target: any) {

}

Used like this像这样使用

@Service
class A {
    id = 'A'

    constructor(foo: Foo, bar: Bar) {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM