如何处理获取异步函数的返回类型?

发布于 2025-01-21 03:54:43 字数 971 浏览 2 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆夏时光 2025-01-28 03:54:43

您可以尝试使用 类型断言

编辑:将类型断言放在正确的位置。

    export const fetchData = async (): Promise<IDataType[]> => {
      try {
        const { data } = await axios.get(url);
        return Object.values(data) as IDataType[];
      } catch (error) {
        return error);
      }
    };

You can try casting the data to your type IDataType[] with Type-Assertion.

Edit: placed the type assertion in the correct place.

    export const fetchData = async (): Promise<IDataType[]> => {
      try {
        const { data } = await axios.get(url);
        return Object.values(data) as IDataType[];
      } catch (error) {
        return error);
      }
    };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文