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

jor*_*dan 29 typescript protractor

我正在使用Typescript开发Protractor测试.似乎可用于量角器的d.ts文件已经过时了.我正在尝试更新它以包括预期条件量角器已添加.(http://www.protractortest.org/#/api?view=ExpectedConditions)总结一下,预期条件是量角器中的一组函数,它返回一个返回值的承诺的函数.

用法示例:

protractor.ExpectedCondtions.visibilityOf(element(by.id('button1')))();
Run Code Online (Sandbox Code Playgroud)

我很难说如何告诉量角器我将返回一个将返回特定返回类型的函数.有人对这个有经验么?

Mar*_*rev 30

如果我理解正确,您的解决方案将取决于"第二个"函数返回的类型.

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

  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;
    }
}
Run Code Online (Sandbox Code Playgroud)


and*_*ras 7

由于此问题首先在Google中弹出,提示如何为返回函数的函数键入return函数,因此我将在此处添加通用解决方案以声明这些类型。

因此,如果您想向该咖喱add函数添加类型声明:

const add = (a : number) => (b: number) => a + b;
Run Code Online (Sandbox Code Playgroud)

您只需复制=符号后的内容,然后将返回值设为相应的值即可:

export const add: (a : number) => (b: number) => number =
    (a : number) => (b: number) => a + b;
Run Code Online (Sandbox Code Playgroud)

但是在这一点上,您不需要实际函数的类型,因此只需键入它即可,就好像是JS:

export const add: (a : number) => (b: number) => number =
    a => b => a + b;
Run Code Online (Sandbox Code Playgroud)

更广泛地编写它:

const add: (a : number) => (b: number) => number =
    a => {
        console.log(a);
        return b => {
            console.log(b);
            return a + b;
        }
    };
Run Code Online (Sandbox Code Playgroud)

使用泛型:

export const add: <A extends number, B extends number>(a : A) => (b: B) => number =
    a => b => a + b;
Run Code Online (Sandbox Code Playgroud)