[英]Typescript - Recursive Function Type
I'm trying to write a recursive typescript family of functions that takes an array with elements of its own type as a parameter. 我正在尝试编写一个递归的打字稿函数系列,该函数系列将具有其自身类型的元素的数组作为参数。
function example(parameter:number, path: {(parameter:number, path:{/*what do I put here?!*/}[]):boolean;}[]) : boolean
{
return false;
}
This means I could call the function with: 这意味着我可以通过以下方式调用该函数:
let result = example(123, [example, example, anotherexample]);
The path / "What do I put here" part is where I'm stuck. 路径/“我在这里放什么”部分是我遇到的问题。 I'd like to put the whole function type into a typedef somehow, also to improve readability.
我想以某种方式将整个函数类型放入typedef中,以提高可读性。
You can declare the type of example
as an interface, so you can refer to it in the type for path
: 您可以将
example
的类型声明为接口,因此可以在path
的类型中引用它:
interface Example {
(parameter: number, path: Example[]): boolean
}
function example(parameter: number, path: Example[]): boolean {
return false;
}
demo on TypeScript Playground TypeScript Playground上的演示
UPD: To explicitly declare the type of example
, you can write it like this: UPD:要明确声明
example
的类型,可以这样编写:
const example : Example = function (parameter: number, path: Example[]): boolean {
return false;
}
This will warn for type errors, but note that it's a constant now, so you won't be able to refer to it before its declaration. 这将警告类型错误,但请注意,它现在是一个常量,因此您将无法在声明它之前引用它。 For more info on interfaces, check out https://www.typescriptlang.org/docs/handbook/interfaces.html
有关接口的更多信息,请查看https://www.typescriptlang.org/docs/handbook/interfaces.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.