【问题标题】:How do I make a function field on an interface take the parameters of a corresponding function interface?如何让接口上的函数字段获取对应函数接口的参数?
【发布时间】:2017-08-13 03:24:18
【问题描述】:

目标

我有一个带有两个参数的私有函数:

export interface XhrHelperFunction extends Function {
    (cb ?: Function, lock ?: boolean) : any;
}

...我有一个公共函数的接口,允许用户调用该私有函数:

export interface Actionable {
    run(cb : Function, lock?: boolean) : void;
}

这种格式的问题是每次更新XhrHelperFunction的接口,我都要相应地更新我的Actionable接口的格式。因此,我更愿意重写Actionable,类似于:run(/* Parameters of XhrHelperFunction */) : void;

尝试

我尝试了以下格式:

export interface Actionable {
    run(XhrHelperFunction) : void;
}

这在类中编写run 方法签名时有效,但在将参数传递到类实例时不起作用,即。 actionable.run(cb, lock) 因为显然参数不符合 function run(XhrHelperFunction) : void 的签名。我也不能将它们括在括号中并将它们转换为XhrHelperFunction

你有什么建议?

【问题讨论】:

    标签: oop generics inheritance typescript interface


    【解决方案1】:

    你可以引入一个参数类型,例如

    interface IArguments {
        cb? : Function;
        lock? : boolean;
    }
    

    并使你的接口依赖于这种类型:

    export interface XhrHelperFunction extends Function {
        (args : IArguments) : any;
    }
    
    export interface Actionable {
        run(arguments : IArguments) : void;
    }
    

    我想知道,当您将一个非常薄的包装器公开为公共 API 时,为什么不首先公开辅助函数。这将降低该接口的复杂性。请注意,如果您发布公共接口,更改函数参数会变得越来越烦人,因为您需要根据Actionable 接口更改所有位置。

    如果您想将XhrHelperFunction 的更改与Actionable 接口的使用者隔离开来,那么无论如何您都不能公开相同的参数类型,您应该保持代码不变。

    【讨论】:

    • 正是我想要的,谢谢。是的,我一直在争论是否直接公开这个函数。主要是,它让我可以选择在调用 Actionable 之前运行初步代码(例如设置一些状态,例如切换锁或类似的),但到目前为止,我已经能够从函数本身内部处理所有事情,所以我或许可以按照你的建议去做。
    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2021-05-19
    • 2019-06-15
    相关资源
    最近更新 更多