1

Is it possible to simplify the declaration of resolve variable in the TypeScript code below, without sacrificing type safety? I'm new to TypeScript, please bear with me.

The goal is to save the promise resolver callback, passed to to the executor function, so it can be invoked later outside it. What I've come up with is let resolve: ((v: number) => void) | null = null. Try it in the TS Playground:

function timeout(ms: number): Promise<number> {
  // save the promise's resolver to be invoked later
  let resolve: ((v: number) => void) | null = null; // <===
  const p = new Promise<number>(r => resolve = r);

  const start = performance.now();
  setTimeout(() => resolve!(performance.now() - start), ms);
  return p;
}

If I don't make it a union type with null, TypeScript will legitly complain that resolve might be uninitialized when I invoke it later: setTimeout(() => resolve(...), ms). Is there a more concise way to do this, without introducing any or TypeScript errors?

To clarify, the above example is a bit contrived, it could be easily simplified like this:

function timeout(ms: number): Promise<number> {
    const start = performance.now();
    return new Promise<number>(r => 
        setTimeout(() => r(performance.now() - start)));
}

The question is however about TypeScript syntax. The actual code does need to save the promise's resolve and reject callbacks to implement the Deferred pattern.

1
  • At some point I had it like this, where | null` and ! were required.
    – noseratio
    Commented Feb 18, 2021 at 23:01

1 Answer 1

1

One way to make it more concise is to remove the nulls and not assign anything to resolve at first:

function timeout(ms: number): Promise<number> {
    let resolve: (v: number) => void;
    const p = new Promise<number>(r => resolve = r);

    const start = performance.now();
    setTimeout(() => resolve(performance.now() - start), ms);
    return p;
}

It may look a bit odd, but this does happen to work with any ! assertion.

If you happen to be able to return the Promise immediately, you could slim it down to

function timeout(ms: number) {
    let resolve: (v: number) => void;
    return new Promise<number>(r => {
        resolve = r;
        const start = performance.now();
        setTimeout(() => resolve(performance.now() - start), ms);
    });
}
6
  • 2
    Yeah, this is where I got also, but I'm not sure why the compiler is happy about that either. If you change p's definition to const p = new Promise<number>(r => void 0); there is no compiler error but you'll get runtime errors about resolve not being a function. I think this is a limitation about callbacks and control flow analysis (like github.com/microsoft/TypeScript/issues/9998). Personally I'd rather do it the original way and use the ! so there's some indication that I know something is amiss here
    – jcalz
    Commented Feb 18, 2021 at 22:08
  • 1
    Looks like it's #9998 (at least github.com/microsoft/TypeScript/issues/22468 indicates that) so it's just another situation where the compiler just hopes for the best when dealing with closed-over values in a callback that isn't immediately invoked inline.
    – jcalz
    Commented Feb 18, 2021 at 22:17
  • Interesting! I swear I was getting a warning about nullability when I started, so I had to union and initialized it with null, then use !. But I can't repro that warning anymore even with my own Playground snippet! Is there a TS flag or anything I might have turned on/off somehow?
    – noseratio
    Commented Feb 18, 2021 at 22:21
  • I see now, at some point I had it like this, where the | null and ! is required. Is there a shorter version for this? cc @jcalz
    – noseratio
    Commented Feb 18, 2021 at 22:39
  • 1
    @noseratio You could leave off the : Promise<number> in the return type if you wanted, TS can infer it automatically. Other than that, if you don't want to go the route in the answer without initial assignment, I don't think so, but the code looks pretty reasonable to me. Commented Feb 18, 2021 at 22:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.