2

[email protected]

In typescript writing definitions for manually curried functions. They work when the final return value is a non-promise, but fail when it is a promise. For example, this works:

function test (
  a: number,
): (
  b: number,
) => number
function test (
  a: number,
  b: number,
 ):  number
function test (a, b?) {
  if (b === undefined)
    return function (b: number) { test(a, b) }
  return a + b
}

While this fails:

function asynctest (
  a: number,
): (
  b: number,
) => Promise<number>
function asynctest (
  a: number,
  b: number,
 ):  Promise<number>
async function asynctest (a, b?) {
  if (b === undefined)
    return function (b: number) { return asynctest(a, b) }
  return await a + b
}

VSCode's built in type inspector suggests that the type returned by asynctest when provided 1 argument is (b: number) => Promise<number> as expected.

1 Answer 1

2

During the writing of this question I solved it.

An async function must return a promise, so in the case of one argument being passed, rather than returning a function, it is returning a Promise of a function. So the correct async-await version is:

function asynctest (
  a: number,
): Promise<(
  b: number,
) => Promise<number>>
function asynctest (
  a: number,
  b: number,
 ):  Promise<number>
async function asynctest (a, b?) {
  if (arguments.length === 1)
    return function (b: number) { return asynctest(a, b) }
  return await a + b
}

The alternative version is using promises directly rather than using async-await (I think this is neater):

function promisetest (
  a: number,
): (
  b: number,
) => Promise<number>
function promisetest (
  a: number,
  b: number,
 ):  Promise<number>
function promisetest (a, b?) {
  if (arguments.length === 1)
    return function (b: number) { return promisetest(a, b) }
  return new Promise(a + b)
}
Sign up to request clarification or add additional context in comments.

Comments

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.