【问题标题】:What is the return type for a function that returns another function返回另一个函数的函数的返回类型是什么
【发布时间】:2015-11-25 17:51:15
【问题描述】:

我正在使用 Typescript 开发 Protractor 测试。看来可用于量角器的 d.ts 文件已经过时了。我正在尝试更新它以包含预期条件量角器有added

总而言之,预期条件是量角器中的一组函数,它们返回一个函数,该函数返回你的值的承诺。

使用示例:

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

我不知道如何告诉量角器我正在返回一个将返回特定返回类型的函数。有人有这方面的经验吗?

【问题讨论】:

  • 不会是Function的返回类型吗?
  • 如果可能的话,我想指出第二个函数的返回类型。不过,“功能”确实有效。

标签: typescript protractor


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    由于这个问题首先在谷歌中弹出,关于如何为返回函数的函数键入返回函数,我将在此处添加通用解决方案来声明这些类型。

    所以如果你想在这个 curried 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-15
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多