Home > Back-end >  Correct typescript async await syntax with typed arrow functions
Correct typescript async await syntax with typed arrow functions

Time:10-23

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.

CodePudding user response:

Try this

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

Or

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

CodePudding user response:

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

  • Related