TypeScript: Call function passed as parameter after delay

I’m making a “callback” system and I’m having trouble with executing after a delay.

public move(onFinish: () => void) {
    let moveTime = 5;
    item.transition.moveBy(new Vector3(0, 0, newHeight - oldHeight), moveTime);
    Time.schedule(() => {
        onFinish();
    }, 5);
}

I’m getting an error that reads, "onFinish is not a function." I believe the problem is that the onFinish(); call is within a second function.

How can I call the onFinish parameter from inside an inner function here?

Hi @24dlau!
The function seems fine for me and should work. Check how you call move and that argument that you pass to it is indeed a function.

Ah, I think I may have pinned down the problem:

The reality is that my onFinish function is an optional parameter and not required:

public move(onFinish?: () => void) {
    …
}

If I call move(); while choosing not to specify anything for onFinish (because it’s optional), would that cause problems if there is an inner call onFinish(); within the function? If so, how would I set this to invoke the function parameter only if the parameter was specified?

All omitted arguments have undefined value. You can wrap the callback in a check like this:

if (onFinish) {
  onFinish()
}

More useful information you can find in a TypeScript handbook.

Ah, that’s great, thank you. I ended up doing a short-form one-liner if like so:

if (onFinish) onFinish();

Thanks for the solution!