0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Much appreciated. I'm new to typescript, so I wasn't sure how to write an interface for just a function type, and your answer has helped me greatly. Small follow-up: Is there a way to declare and define "function example" based on this type? (maybe more trouble tan what it's worth). let example : Step = /* what now? */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.