Axios响应类型允许不正确的代码,

zmeyuzjn  于 8个月前  发布在  iOS
关注(0)|答案(4)|浏览(148)

Describe the bug

The following code should fail type checking but does not:

  1. interface SomeBody {
  2. field1: string;
  3. field2: string;
  4. }
  5. async function fetchSomething(): Promise<SomeBody > {
  6. // Buggy code is missing a call to .data on the AxiosResponse
  7. return await axios.get('http://example.com/some/api'); // TypeScript is fine, but it should not be
  8. }

If you introduce an intermediate variable typechecking does fail:

  1. async function fetchSomething(): Promise< SomeBody > {
  2. const response = await axios.get('http://example.com/some/api');
  3. return response; // TS2322: Type AxiosResponse<any, any> is not assignable to type SomeBody
  4. }

To Reproduce

See https://codesandbox.io/p/sandbox/axios-ts-bug-gty2pg?file=%2Findex.ts%3A20%2C1

Code snippet

  • No response*

Expected behavior

The following code fails type checking as it does when an intermediate variable is introduced:

  1. interface SomeBody {
  2. field1: string;
  3. field2: string;
  4. }
  5. async function fetchSomething(): Promise<SomeBody > {
  6. // Buggy code is missing a call to .data on the AxiosResponse
  7. return await axios.get('http://example.com/some/api'); // TypeScript is fine, but it should not be
  8. }

See microsoft/TypeScript#56532 for a possible fix to the typings.

Axios Version

1.6.2

Adapter Version

  • No response*

Browser

N/A

Browser Version

N/A

Node.js Version

18.18.2

OS

MacOS

Additional Library Versions

  1. N/A

Additional context/Screenshots

  • No response*
ie3xauqp

ie3xauqp1#

你好,@josephearl 。我想为这个问题做出贡献,你能把我分配到这个任务吗?谢谢。

pdkcd3nj

pdkcd3nj2#

@Vayras 我不是axios的维护者,所以不能分配问题,但请随意处理,因为据我所知,没有人在处理这个问题,我相信一个PR会受到欢迎。

vdzxcuhz

vdzxcuhz3#

感谢你告诉我,我一定会解决这个问题。

vom3gejh

vom3gejh4#

我们能确定这是Axios的bug吗?我向Bard询问了这个问题。请告诉我你的看法。
提示1: https://g.co/bard/share/f351e5b2eeec
提示2: https://g.co/bard/share/a263ce7031ff
这似乎就是TypeScript在遇到异步函数时的行为。

相关问题