TypeScript 对在 RTK query 中为查询添加返回类型时会出现以下错误。

huangapple go评论90阅读模式
英文:

TypeScript gives following error for adding a return type for query in RTK query

问题

你可以如下为API调用的数据分配类型:

interface Args {
  postId: string;
  employeeId: string;
}

interface ApiResponse {
  url: string;
  method: string;
  headers: {
    'Content-Type': string;
  };
  // 这里添加API响应的其他属性
}

const apiWithTaggedEndpoints = apiWithTag.injectEndpoints({
  endpoints: builder => ({
    curriculumDetails: builder.query<ApiResponse, Args>({
      query: payload => ({
        url: `/${payload.postId}/${payload.employeeId}`,
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      }),
    }),
  }),
  overrideExisting: true,
});

这个代码为API调用的响应数据定义了一个名为ApiResponse的接口,并在builder.query中使用它来指定API调用的响应类型。这应该解决你的类型分配问题。

英文:

My code is as below:

interface CurriculumDetailsApi {
  curriculum_id: number;
  curriculum_name: string;
  description: string;
  percentage_of_completion: number;
  post_id: string;
  post_type: string;
  topics: Topics[];
}

const apiWithTaggedEndpoints = apiWithTag.injectEndpoints({
  endpoints: builder =&gt; ({
    curriculumDetails: builder.query&lt;CurriculumDetailsApi, input&gt;({
      query: payload =&gt; ({
        url: `/${payload.postId}/${payload.employeeId}`,
        method: &#39;GET&#39;,
        headers: {
          &#39;Content-Type&#39;: &#39;application/json&#39;,
        },
      }),
    }),
  }),
  overrideExisting: true,
&gt; });

I get an error like this:

Type &#39;(payload: Args) =&gt; { url: string; method: string; headers: { &#39;Content-Type&#39;: string; }; }&#39; is not assignable to type &#39;(arg: Args) =&gt; string&#39;.
  Type &#39;{ url: string; method: string; headers: { &#39;Content-Type&#39;: string; }; }&#39; is not assignable to type &#39;string&#39;.ts(2322)
endpointDefinitions.d.ts(36, 5): The expected type comes from property &#39;query&#39; which is declared here on type &#39;Omit&lt;EndpointDefinitionWithQuery&lt;Args, BaseQueryFn&lt;string, unknown, { reason: string; }, { shout?: boolean | undefined; }, { timestamp: number; }&gt;, CurriculumDetailsApi&gt; &amp; { ...; } &amp; { ...; } &amp; QueryExtraOptions&lt;...&gt;, &quot;type&quot;&gt; | Omit&lt;...&gt;&#39;

How can I assign a type to the data from the API call?

答案1

得分: 1

以下是已翻译的内容:

问题出在您如何定义了您的baseQuery上。

我可以看到错误消息中提到,您的baseQuery只能接受一个string参数。您的端点上的query属性返回了您的API的baseQuery的参数。由于您的baseQuery只接受一个string,您只能返回一个string。返回这个对象会导致错误。

Type '{ url: string; method: string; headers: { 'Content-Type': string; }; }' is not assignable to type 'string'.ts(2322)

如果我使用标准的fetchBaseQuery作为API的baseQuery,则不会从此代码中得到任何错误。那个baseQuery可以接受一个string或一个FetchArgs对象,这就是您在这里返回的内容。

您必须修改您的baseQuery,以便它可以接受string | FetchArgs

以下是您的baseQuery的类型,如您的错误消息中所示:

BaseQueryFn<
  string, // Args
  unknown, // Result
  { reason: string; }, // Error
  { shout?: boolean | undefined; }, // DefinitionExtraOptions
  { timestamp: number; } // Meta
>

这里的第一个泛型参数 Args 在这里是关键。

英文:

The issue here will be in how you have defined your baseQuery.

I can see in the error message that your baseQuery can only accept a string argument. The query property on your endpoint returns the arguments for the baseQuery of your API. Since your baseQuery only accepts a string, you can only return a string. Returning this object gives an error.

> ```
> Type '{ url: string; method: string; headers: { 'Content-Type':
> string; }; }' is not assignable to type 'string'.ts(2322)

I don't get any errors from this code if I am using a standard fetchBaseQuery as the baseQuery for the API. That baseQuery will accept either a string or a FetchArgs object, which is what you are returning here.

You must modify your baseQuery so that it can accept string | FetchArgs.


Here are the types for your baseQuery, as shown in your error message:

BaseQueryFn&lt;
  string, // Args
  unknown, // Result
  { reason: string; }, // Error
  { shout?: boolean | undefined; }, // DefinitionExtraOptions
  { timestamp: number; } // Meta
&gt;

The first generic, Args, is the one which matters here.

huangapple
  • 本文由 发表于 2023年1月6日 12:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定