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 => ({
curriculumDetails: builder.query<CurriculumDetailsApi, input>({
query: payload => ({
url: `/${payload.postId}/${payload.employeeId}`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}),
}),
}),
overrideExisting: true,
> });
I get an error like this:
Type '(payload: Args) => { url: string; method: string; headers: { 'Content-Type': string; }; }' is not assignable to type '(arg: Args) => string'.
Type '{ url: string; method: string; headers: { 'Content-Type': string; }; }' is not assignable to type 'string'.ts(2322)
endpointDefinitions.d.ts(36, 5): The expected type comes from property 'query' which is declared here on type 'Omit<EndpointDefinitionWithQuery<Args, BaseQueryFn<string, unknown, { reason: string; }, { shout?: boolean | undefined; }, { timestamp: number; }>, CurriculumDetailsApi> & { ...; } & { ...; } & QueryExtraOptions<...>, "type"> | Omit<...>'
How can I assign a type to the data from the API call?
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<
string, // Args
unknown, // Result
{ reason: string; }, // Error
{ shout?: boolean | undefined; }, // DefinitionExtraOptions
{ timestamp: number; } // Meta
>
The first generic, Args
, is the one which matters here.