简体   繁体   中英

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.

You can declare the type of example as an interface, so you can refer to it in the type for path :

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

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

demo on TypeScript Playground

UPD: To explicitly declare the type of example , you can write it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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