返回另一个函数

时间:2015-11-25 17:51:16

标签: typescript protractor

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

使用示例:

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

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

2 个答案:

答案 0 :(得分:22)

如果我理解正确,你的解决方案将取决于“第二个”函数返回的类型。

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

  1. Lambda语法
  2. 接口(普通接口和通用接口)
  3. 我试着在下面的代码中解释所有这些,请检查一下:

    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;
        }
    }
    

答案 1 :(得分:0)

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

因此,如果您想向此咖喱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;
        }
    };

使用泛型:

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