【问题标题】:Typescript get type constructor of each arguments of a constructorTypescript获取构造函数的每个参数的类型构造函数
【发布时间】: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

【问题讨论】:

标签: javascript typescript dependency-injection annotations static-typing


【解决方案1】:

通过查看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) {
    }
}

【讨论】:

    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多