使用TypeScript装饰器访问扩展类的属性和方法

时间:2017-01-18 04:00:32

标签: node.js express typescript decorator

我正在研究我的快速应用程序的实验性重构,并选择使用TypeScript,因为我更喜欢用任何语言进行强类型输入。我看到了使用TypeScript的装饰器作为一种强大的方法来构建一个结构良好的项目作为DRY的潜力。

我在从一个类扩展的类中访问属性时遇到问题,我在这个类中设置了装饰器。

示例:

class BaseRouter {

    app: express.Application = express;

    // some other common stuff
}

function PostMethod(route: string = '/') {

    return (target: BaseRouter, key: string, descriptor: PropertyDescriptor): void {

        // This is where things don't work out
        // descriptor.value correctly returns the RequestHandler which I can attach to express
        // target.app is undefined
        target.app.post(route, descriptor.value);
    }
}

router.ts

@ResourceRouter() // <= this is optional, can I access all decorators inside the class from this decorator? That would also lead me to a solution
export class BlogRouter extends BaseRouter {


    @GetMethod()
    index(req, res) {

        // req.send(...); return posts
    }


    @GetMethod('/:modelId')
    show(req, res, next) {

         // find req.params.modelId
    }

    @PostMethod()
    createPost() {}

    @DeleteMethod()
    deletePost() {}

    @UpdateMethod()
    updatePost() {}
}

我知道这并不完美我现在只是尝试装饰器,因为我已经成功地将它们用于其他非常有效的场景中。请注意,这与Angular 2+无关。

0 个答案:

没有答案
相关问题