简化打字稿装饰器功能

时间:2018-09-15 13:50:11

标签: typescript

我在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。”

1 个答案:

答案 0 :(得分:2)

让我们分解一下,赋值(=)左侧的所有内容都是一个声明,右侧的所有内容均是值:

const component: (options: MyCustomOptions) => Function

声明一个常量component,该常量是一个接受MyCustomOptions并返回Function的函数。然后在=之后……

(options: MyCustomOptions): Function

接受MyCustomOptions并返回Function的函数。从打字的角度来看,此后的所有内容均无关紧要,但其余的是:

 => (controller: string) => { /* … */ return options; }

要返回的Function是哪个:取一个string并返回一个MyCustomOptions。请注意,声明未指定此函数的参数和返回值,只需将其设为Function

您可以通过类型推断来消除很多冗余,并获得相同的结果:

const component = (options: MyCustomOptions): Function => (controller: string) => { /* … */ return options; }

从技术上讲,您可以不包含: Function部分,因为它可以推断出来,但可以推断为(string) => MyCustomOptions而不是Function