Typescript接口:返回泛型函数的方法

时间:2017-03-03 01:14:41

标签: function typescript interface closures

有人知道如何为类方法定义接口,如:

Public Function abc() As Integer
    abc = 0
End Function

我对此感到头疼,基本上如何将参数类型(和返回值)定义为Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub If Target.Formula = "=abc()" Then Me.Cells(1, 2).Value = 2 End If End Sub

1 个答案:

答案 0 :(得分:1)

我想你想要返回另一个具有相同类型fn的函数。

class Wrapper {

    // generic for any fn, without handling parameter type
    // a return type is not required: tsc infers from `return` statement.
    wrap<T extends Function>(fn: T) {
        return function () {
            // NOTE this version does not handle types of parameters.
            // you will have to use `arguments`
            return fn();
        } as any as T;
    }

    // generic for all unary fn
    // we can have correct type of arg1 in this way
    wrapF1<P1, R>(fn: (arg1: P1) => R) {
        const wrapped = function (arg1: P1) {
            return fn(arg1);
        }
        return wrapped;
    }

    // wrapF2, wrapF3, if you need more
}