js获取TS,不可赋值



为什么我在TS中收到此警告?

Type 'unknown' is not assignable to type 'PokemonList'.ts(2322)

这个错误出现在第行:";返回e";

代码:


export interface PokemonList {
count: number;
next: string;
previous?: any;
results: {
name: string;
url: string;
}[]
};

const PokeApi = async (): Promise<PokemonList> => {
try {
const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10');
return res.json()
} catch(e) {
return e;
}
};

如果我做这个:

( Promise<PokemonList> | unknown )

然后我得到这个错误:

The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<unknown>'?ts(

该函数的返回类型为

Promise<PokemonList | Error>

正如基思所说;这不是一个好主意,你现在已经打破了你的承诺链&";。Promises具有.catch,并在try/catch中工作以将Promises链接在一起。你所拥有的东西需要if(/else)支票,这不是Promises的本意。

要解决这个问题,您应该删除函数中的try/catch块,并在调用catch时使用它来处理错误。

const PokeApi = async (): Promise<PokemonList> => {
const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10');
return res.json()
};
// when calling it inside async function
let pokemonList: PokemonList;
try {
pokemonList = await PokeApi();
} catch (e) {
// Handle error
}

最新更新