TypeScript异步箭头函数类型语法问题:解决ts(1055)报错
TypeScript中async函数返回类型报错的解决方法
问题背景
我想在TypeScript中使用async/await,参考JS的写法:
const foo = async () => { // do something }
自己尝试写了这段代码:
export const fetchAirports = async (): Airport[] => { //More code return airports; };
但遇到错误:
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.
我必须指定返回类型,否则就失去了TypeScript的意义,求解决办法。
解决方法
在TypeScript中,所有async函数的返回值都会被自动包装成Promise,所以你不能直接把返回类型声明为Airport[],必须用Promise<Airport[]>来表示这个异步函数最终会返回一个解析为Airport[]的Promise。
修正后的代码如下:
export const fetchAirports = async (): Promise<Airport[]> => { //More code return airports; };
这样就能解决ts(1055)的错误,同时保留了TypeScript的类型检查能力。
内容的提问来源于stack exchange,提问作者Amos Machora
相关产品推荐
相关产品推荐

