繁体   English   中英

打字稿-递归函数类型

[英]Typescript - Recursive Function Type

我正在尝试编写一个递归的打字稿函数系列,该函数系列将具有其自身类型的元素的数组作为参数。

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中,以提高可读性。

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

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

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

TypeScript Playground上的演示

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM