- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
typescript 中是否有任何习惯用法来定义与方法定义内联的类中的方法的属性?
我正在寻找类似于 .NET 属性的内容。
这是我到目前为止所得到的示例
class FooController {
foo(req: express.Request, res: express.Response) {
res.send(JSON.stringify({ loc: 'FooController::foo 2 here '+req.params.fooId }));
}
bar(req: express.Request, res: express.Response) {
res.send(JSON.stringify({ loc: 'FooController::bar here' }));
}
}
FooController.prototype.foo['route'] = '/foo/:fooId';
FooController.prototype.foo['verb'] = 'get';
FooController.prototype.bar['route'] = '/bar';
FooController.prototype.bar['verb'] = 'post';
在调用任何 FooController 方法之前,不同的函数将使用 FooController 并询问方法属性以设置路由表。
我不喜欢我的方法定义和我的属性定义之间的距离,尤其是当我的方法变得越来越大并且支持函数位于两者之间时。
这里有什么我可以做的更好的吗?如果除了属性之外,我应该使用不同的语言功能来表达这一点,我对此持开放态度。如果解决方案保留类型安全,我特别感兴趣。
我做了评论build a function object with properties in typescript但由于延迟绑定(bind)和对象方法要求,我不认为那里的解决方案很匹配。
我在 Visual Studio 2013 Update 3 中使用 1.0.3 版的 typescript 编译器。
最佳答案
这是 TypeScript 装饰器的理想候选者:https://github.com/Microsoft/TypeScript/issues/2249 .您重构的代码:
class FooController {
@route(/*put your config here*/)
foo(req: express.Request, res: express.Response) {
res.send(JSON.stringify({ loc: 'FooController::foo 2 here '+req.params.fooId }));
}
@route(/*put your config here*/)
bar(req: express.Request, res: express.Response) {
res.send(JSON.stringify({ loc: 'FooController::bar here' }));
}
}
请注意,您将需要很快就会发布的 TypeScript 1.5。
关于attributes - Typescript 惯用语将属性添加到与方法定义内联的方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29327091/
Tcl 有 apply和 lambda , 但没有闭包。 从 tcl 8.6 开始,什么是惯用形式或闭包? 已发布 patterns看起来很困惑,下面的也是如此。 例子: #!/usr/bin/env
是否有可能以某种方式完成以下操作: x.hpp - 此文件包含在许多其他类中 class x_impl; //forward declare class x { public:
我使用 Idiorm作为 MySQL 和 PHP 的 ORM。 我需要检查表是否已创建。 在 SQL 中 这在 phpMyAdmin 中有效 SHOW TABLES LIKE 'ro_globals'
假设我们有一个返回一些值和错误的函数。处理错误和值声明的首选方式是什么? func example_a(data interface{}) (interface{}, error) { var
这样的事情存在吗? ruby : if __FILE__ == $0 main end Perl: unless(caller) { main; } 卢阿: if type(packa
我正在阅读以下问题: What is the copy-and-swap idiom? 我的印象是,当按值传递对象时,它的指针和值会被复制,但被传递对象的指针指向的内存不会被复制。因此,当从链接到示例
Java tryLock(long time, TimeUnit unit)可以用作获取锁的非阻塞尝试。如何实现python中的等价物? (首选 Pythonic | idiomatic 方式!) J
我正在阅读 J. Bloch 的《effective Java》一书,现在正阅读有关惰性初始化的部分。考虑以下类: public class LazyInit{ public static g
我最近一直在写一些 Clojure,我发现自己经常使用以下模式: (let [x (bam) y (boom)] {:x x :y y}) 所以我继续写了下面的宏: (defma
我开始玩 Go,对 new 函数有点恼火。它似乎非常有限,尤其是在考虑具有匿名字段或内联初始化的结构时。所以我通读了规范和 stumbled over the following paragraph
Python 库公开一个通用的“opener”函数并不少见,它接受一个字符串作为它们的主要参数,该字符串可以表示一个本地文件名(它将打开并对其进行操作),一个 URL(它将下载并对其进行操作)或数据(
我想了解一些 Perl 用于逐块读取文本文件的代码。 文本文件 MYFILE看起来像这样: First block First Line: Something in here Second Line:
我是一名优秀的程序员,十分优秀!