#
Usage With TypeScriptWhat You'll Learn
- Details on how to use various RTK Query APIs with TypeScript
#
IntroductionAs with the rest of the Redux Toolkit package, RTK Query is written in TypeScript, and its API is designed for seamless use in TypeScript applications.
This page provides details for using APIs included in RTK Query with TypeScript and how to type them correctly.
info
We strongly recommend using TypeScript 4.1+ with RTK Query for best results.
If you encounter any problems with the types that are not described on this page, please open an issue for discussion.
createApi
#
#
Using auto-generated React HooksThe React-specific entry point for RTK Query exports a version of createApi
which automatically generates React hooks for each of the defined query & mutation endpoints
.
To use the auto-generated React Hooks as a TypeScript user, you'll need to use TS4.1+.
- TypeScript
- JavaScript
For older versions of TS, you can use api.endpoints.[endpointName].useQuery/useMutation
to access the same hooks.
- TypeScript
- JavaScript
baseQuery
#
Typing a Typing a custom baseQuery
can be done using the BaseQueryFn
type exported by RTK Query.
The BaseQueryFn
type accepts the following generics:
Args
- The type for the first parameter of the function. The result returned by aquery
property on an endpoint will be passed here.Result
- The type to be returned in thedata
property for the success case. Unless you expect all queries and mutations to return the same type, it is recommended to keep this typed asunknown
, and specify the types individually as shown below.Error
- The type to be returned for theerror
property in the error case. This type also applies to allqueryFn
functions used in endpoints throughout the API definition.DefinitionExtraOptions
- The type for the third parameter of the function. The value provided to theextraOptions
property on an endpoint will be passed here.Meta
- the type of themeta
property that may be returned from calling thebaseQuery
. Themeta
property is accessible as the second argument totransformResponse
.
note
The meta
property returned from a baseQuery
will always be considered as potentially undefined, as a throw
in the error case may result in it not being provided. When accessing values from the meta
property, this should be accounted for, e.g. using optional chaining
- TypeScript
- JavaScript
endpoints
#
Typing query and mutation endpoints
for an api are defined as an object using the builder syntax. Both query
and mutation
endpoints can be typed by providing types to the generics in <ResultType, QueryArg>
format.
ResultType
- The type of the final data returned by the query, factoring an optionaltransformResponse
.- If
transformResponse
is not provided, then it is treated as though a successful query will return this type instead. - If
transformResponse
is provided, the input type fortransformResponse
must also be specified, to indicate the type that the initial query returns. The return type fortransformResponse
must matchResultType
. - If
queryFn
is used rather thanquery
, then it must return the following shape for the success case:
- If
QueryArg
- The type of the input that will be passed as the only parameter to thequery
property of the endpoint, or the first parameter of aqueryFn
property if used instead.
- TypeScript
- JavaScript
note
queries
and mutations
can also have their return type defined by a baseQuery
rather than the method shown above, however, unless you expect all of your queries and mutations to return the same type, it is recommended to leave the return type of the baseQuery
as unknown
.
queryFn
#
Typing a As mentioned in Typing query and mutation endpoints, a queryFn
will receive its result & arg types from the generics provided to the corresponding built endpoint.
- TypeScript
- JavaScript
The error type that a queryFn
must return is determined by the baseQuery
provided to createApi
.
With fetchBaseQuery
, the error type is like so:
An error case for the example above using queryFn
and the error type from fetchBaseQuery
could look like:
- TypeScript
- JavaScript
For users who wish to only use queryFn
for each endpoint and not include a baseQuery
at all, RTK Query provides a fakeBaseQuery
function that can be used to easily specify the error type each queryFn
should return.
- TypeScript
- JavaScript
providesTags
/invalidatesTags
#
Typing RTK Query utilizes a cache tag invalidation system in order to provide automated re-fetching of stale data.
When using the function notation, both the providesTags
and invalidatesTags
properties on endpoints are called with the following arguments:
- result:
ResultType
|undefined
- The result returned by a successful query. The type corresponds withResultType
as supplied to the built endpoint. In the error case for a query, this will beundefined
. - error:
ErrorType
|undefined
- The error returned by an errored query. The type corresponds withError
as supplied to thebaseQuery
for the api. In the success case for a query, this will beundefined
. - arg:
QueryArg
- The argument supplied to thequery
property when the query itself is called. The type corresponds withQueryArg
as supplied to the built endpoint.
A recommended use-case with providesTags
when a query returns a list of items is to provide a tag for each item in the list using the entity ID, as well as a 'LIST' ID tag (see Advanced Invalidation with abstract tag IDs).
This is often written by spreading the result of mapping the received data into an array, as well as an additional item in the array for the 'LIST'
ID tag. When spreading the mapped array, by default, TypeScript will broaden the type
property to string
. As the tag type
must correspond to one of the string literals provided to the tagTypes
property of the api, the broad string
type will not satisfy TypeScript. In order to alleviate this, the tag type
can be cast as const
to prevent the type being broadened to string
.
- TypeScript
- JavaScript
skipToken
#
Skipping queries with TypeScript using RTK Query provides the ability to conditionally skip queries from automatically running using the skip
parameter as part of query hook options (see Conditional Fetching).
TypeScript users may find that they encounter invalid type scenarios when a query argument is typed to not be undefined
, and they attempt to skip
the query when an argument would not be valid.
- TypeScript
- JavaScript
While you might be able to convince yourself that the query won't be called unless the id
arg is a number
at the time, TypeScript won't be convinced so easily.
RTK Query provides a skipToken
export which can be used as an alternative to the skip
option in order to skip queries, while remaining type-safe. When skipToken
is passed as the query argument to useQuery
, useQueryState
or useQuerySubscription
, it provides the same effect as setting skip: true
in the query options, while also being a valid argument in scenarios where the arg
might be undefined otherwise.