1

As you may know, functions in JavaScript can have properties as any object. For example (taken from the excellent JavaScript: The Definitive Guide, 6th ed, p. 178) computes a factorial using the function as memoization array:

function factorial(n: number): number {
  if (isFinite(n) && n > 0 && n == Math.round(n)) {
    if (!(n in factorial))
      factorial[n] = n * factorial(n - 1);
    return factorial[n];
  }
  else
    return NaN;
}
factorial[1] = 1;

I tried defining the following interface:

interface Factorial {
  (n: number) : number;
  [ index: number ]: number;
}

But the compiler is telling me that Type '(n: number) => number' is not assignable to type 'Factorial'. Index signature is missing in type '(n: number) => number'. I can't do the obvious thing and just define private index: number; inside the function, I'm stumped.

1 Answer 1

1

What you have is an example of hybrid types. You have to use type assertion to make sure the function complies with the interface:

let factorial = function (n: number): number {
    if (isFinite(n) && n > 0 && n == Math.round(n)) {
        if (!(n in factorial))
            factorial[n] = n * factorial(n - 1);
        return factorial[n];
    }
    else
        return NaN;
} as Factorial;

factorial[1] = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Thought there was a better way, but I guess this is it. It does the trick. Thanks

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.