Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct typescript async await syntax with typed arrow functions

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.

like image 417
Amos Machora Avatar asked Jan 24 '26 23:01

Amos Machora


2 Answers

Try this

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

Or

export const fetchAirports = async (): Promise<Array<Airport>> => {
    //More code
    return airports;
}
like image 102
Saurav Ghimire Avatar answered Jan 26 '26 14:01

Saurav Ghimire


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

like image 30
Medlide Avatar answered Jan 26 '26 15:01

Medlide