如何处理获取异步函数的返回类型?
我有一个fetchdata
函数:
export const fetchData = async (): Promise<IDataType[]> => {
try {
const { data } = await axios.get<IDataType>(url);
return Object.values(data);
} catch (error) {
return error);
}
};
VS代码显示错误。 Typescript不允许返回此功能的未知类型:
Type 'unknown' is not assignable to type 'IDataType[]'.
我更改了代码行。它在工作。但是,我不确定这是否是正确的方法:
export const fetchData = async (): Promise<IDataType[]> => {
try {
const { data } = await axios.get<IDataType>(url);
return Object.values(data);
} catch (error) {
return new Promise((resolve, reject) => reject(`${error}`));
}
};
如您所见,我添加了新的Promise
关键字。有什么最佳实践吗?我想从组件达到此功能。
例如:
useEffect(() => {
getData();
}, []);
const getData = async () => {
const fetchedData = await fetchData();
...
};
I have a fetchData
function like this:
export const fetchData = async (): Promise<IDataType[]> => {
try {
const { data } = await axios.get<IDataType>(url);
return Object.values(data);
} catch (error) {
return error);
}
};
VS Code shows an error. TypeScript doesn't allow to return unknown type for this function:
Type 'unknown' is not assignable to type 'IDataType[]'.
I changed a line of code. It's working. However, I'm not sure whether it's the right way to do it or not:
export const fetchData = async (): Promise<IDataType[]> => {
try {
const { data } = await axios.get<IDataType>(url);
return Object.values(data);
} catch (error) {
return new Promise((resolve, reject) => reject(`${error}`));
}
};
As you can see, I added a new Promise
keyword. Are there any best practices for it? I want to reach this function from components.
For example:
useEffect(() => {
getData();
}, []);
const getData = async () => {
const fetchedData = await fetchData();
...
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用 类型断言。
编辑:将类型断言放在正确的位置。
You can try casting the data to your type
IDataType[]
with Type-Assertion.Edit: placed the type assertion in the correct place.