3

Similar question for vanilla JS here. I however want to use async await with typescript function as below.

Javascript

const foo = async () => {
  // do something
}

Initial attempt

export const fetchAirports = async (): Airport[] => {
  //More code
  return airports;
};

but i get an error ts(1055) Type 'Airport[]' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. which to me sounds like a lot of jargon. Please remember I have to specify a return type in the function declaration otherwise it nullifies the need for typescript in the first place.

2
  • 2
    JavaScript async function will always return a Promise. Try changing the return type Airport[] you specified to Promise<Airport[]> Commented Oct 22, 2022 at 8:46
  • It's not a syntax problem, it's a type problem. An async function cannot return something that's not a promise. Commented Oct 22, 2022 at 8:50

2 Answers 2

4

Try this

export const fetchAirports = async (): Promise<Airport[]> => {
    //More code
    return airports;
}

Or

export const fetchAirports = async (): Promise<Array<Airport>> => {
    //More code
    return airports;
}
Sign up to request clarification or add additional context in comments.

Comments

2

When you use async function, it wraps return value in Promise, so instead Airport[] you should wrap it in Promise like this: Promise<Airport[]>

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.