返回另一个函数的函数的返回类型是什么?

79

我正在使用Typescript开发Protractor测试。看起来,可用于protractor的d.ts文件非常过时。我正试图更新它以包括protractor添加的“Expected Conditions”

总结一下,预期条件是protractor中返回值为Promise的函数集合。

以下是使用示例:

protractor.ExpectedCondtions.visibilityOf(element(by.id('button1')))();

我不知道该如何告诉Protractor,我正在返回一个将返回特定返回类型的函数。 有人有相关经验吗?


返回类型不应该是 Function 吗? - tymeJV
如果可能的话,我想指定第二个函数的返回类型。不过,“Function”也可以。 - jordan
2个回答

54

如果我理解你的意思正确的话,你的解决方案将取决于“second”函数返回的类型。

简而言之,有至少两种方法可以做到这一点:

  1. 使用Lambda语法
  2. 接口(普通和泛型接口)

我已经在下面的代码中尝试解释了所有这些,请检查一下:

module main
{
    export class TestClass
    {
        // Use lamba syntax as an interface for a return function
        protected returnSpecificFunctionWhichReturnsNumber(): () => number
        {
            return this.specificFunctionWhichReturnsNumber;
        }

        protected specificFunctionWhichReturnsNumber(): number
        {
            return 0;
        }

        // Use an interface to describe a return function
        protected returnSpecificInterfaceFunction(): INumberFunction
        {
            return this.specificFunctionWhichReturnsNumber;
        }

        // Use a generic interface to describe a return function
        protected returnSpecificGenericInterfaceFunction(): IReturnFunction<number>
        {
            return this.specificFunctionWhichReturnsNumber;
        }
    }

    // An interface for a function, which returns a number
    export interface INumberFunction
    {
        (): number;
    }

    // A generic interface for a function, which returns something
    export interface IReturnFunction<ValueType>
    {
        (): ValueType;
    }
}

46

由于这个问题在谷歌搜索中首先弹出,因此我将在此处添加一般性解决方案,以声明返回函数的函数的类型。

因此,如果您想要为此柯里化的add函数添加类型声明:

const add = (a : number) => (b: number) => a + b;

你只需复制等号=后面的内容,并将返回值设为相应的值:

export const add: (a : number) => (b: number) => number =
    (a : number) => (b: number) => a + b;

但是此时,你不需要实际函数的类型,所以你可以只键入这个,就像它是JS一样:

export const add: (a : number) => (b: number) => number =
    a => b => a + b;
写得更详细一些:

写得更详细一些:

const add: (a : number) => (b: number) => number =
    a => {
        console.log(a);
        return b => {
            console.log(b);
            return a + b;
        }
    };

使用 function:

function add(a: number): (b: number) => number {
    return function(b) {
        return a + b
    }
}

使用泛型:

export const add: <A extends number, B extends number>(a : A) => (b: B) => number =
    a => b => a + b;

或者使用function(根据用法,B extends number可以与A extends number在同一位置):

function add<A extends number>(a: A): <B extends number>(b: B) => number {
    return function(b) {
        return a + b
    }
}

如果您将函数声明为function(而非使用const声明为匿名函数),那么这会如何改变? - Rax Adaam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接