[英]Simplify Typescript decorator function
我在Typescript中遇到了以下装饰器:
const component: (options: MyCustomOptions) => Function = (options: MyCustomOptions): Function => (controller: string) => {
// do some things
options.controller = controller;
return options;
};
export interface MyCustomOptions extends angular.IComponentOptions {}
第一行看起来很复杂,我很想对其进行重构,但是我不明白它的作用。 有人可以指导我如何解释这段代码吗?
我的最佳尝试是遵循以下几行:
// component is declared as a function that accepts 1 parameter of type MyCustomOptions,
// but the output type is unclear (I can infer from the body `return options` later on
// that this will be of type MyCustomOptions as well, but I can't see this here)
const component: (options: MyCustomOptions) => Function
// a) I am lost at the double declaration here
// options is declared as MyCustomOptions, and then as a Function?
// b) I also don't understand where the controller comes from or what it does
// Is it a parameter? What's the difference with options?
= (options: MyCustomOptions): Function => (controller: string) => {
TSLint抱怨使用Function
: “避免使用Function
类型。建议使用特定的函数类型,例如() => void
。”
让我们分解一下,赋值( =
)左侧的所有内容都是一个声明,右侧的所有内容都是值:
const component: (options: MyCustomOptions) => Function
声明一个常量component
,该component
是一个函数,它接受MyCustomOptions
并返回Function
。 然后在=
…之后
(options: MyCustomOptions): Function
一个接受MyCustomOptions
并返回Function
。 从键入的角度来看,此后的所有内容均无关紧要,但其余的是:
=> (controller: string) => { /* … */ return options; }
返回的是哪个Function
:接受string
并返回MyCustomOptions
的Function
。 注意,该函数的参数和返回值不是由声明指定的,只需要一个be Function
。
您可以通过类型推断消除很多冗余,并获得相同的结果:
const component = (options: MyCustomOptions): Function => (controller: string) => { /* … */ return options; }
从技术上讲,您可以避免不包含: Function
部分,因为可以推断出它,但可以推断为(string) => MyCustomOptions
而不是Function
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.