打字稿 - 递归函数类型

时间:2017-10-28 16:10:59

标签: typescript recursion

我正在尝试编写一个递归的typescript系列函数,它将一个带有自己类型元素的数组作为参数。

function example(parameter:number, path: {(parameter:number, path:{/*what do I put here?!*/}[]):boolean;}[]) : boolean
{
    return false;
}

这意味着我可以通过以下方式调用该函数:

let result = example(123, [example, example, anotherexample]);

路径/“我在这里放什么”部分是我被困住的地方。我想以某种方式将整个函数类型放入typedef中,以提高可读性。

1 个答案:

答案 0 :(得分:1)

您可以将example的类型声明为接口,因此您可以在path的类型中引用它:

interface Example {
  (parameter: number, path: Example[]): boolean
}

function example(parameter: number, path: Example[]): boolean {
  return false;
}

demo on TypeScript Playground

UPD:要明确声明example的类型,您可以这样写:

const example : Example = function (parameter: number, path: Example[]): boolean {
  return false;
}

这会警告类型错误,但请注意它现在是常量,所以在声明之前你将无法引用它。有关接口的更多信息,请查看https://www.typescriptlang.org/docs/handbook/interfaces.html

相关问题