如何在 redux-toolkit 中输入 provideTags(许多项目端点)
2022-06-06
2062
以下代码运行良好,但我无法正确输入
providesTags
:
type Post = {
id: number,
name: string,
description: string,
}
const postsApiSlice = api.injectEndpoints({
endpoints: (builder) => ({
getPosts: builder.query<EntityState<Post>, void>({
query: ROUTES.POSTS,
transformResponse: (responseData: Post[]) => {
return adapter.setAll(initialState, responseData)
},
// Typescript error is here, at provideTags
providesTags: (result) => {
// What to do if result is undefined?
if (!result) return [{ type: POST_TAG, id: 'LIST' }]
const tags = (result.ids.length > 0) ?
// Typescript accepts type of next line if I return it
result.ids.map((id) => ({ type: POST_TAG, id }))
:
// Typescript also accepts type of next line if I return it
[{ type: POST_TAG, id: 'LIST' }]
return tags
}
}),
}),
})
我收到 Typescript 错误:
Type '(result: EntityState<Post> | undefined) => { type: string; id: EntityId; }[]' is not assignable to type 'ResultDescription<"Post", EntityState<Post>, void, FetchBaseQueryError, {} | undefined> | undefined'.
Type '(result: EntityState<Post> | undefined) => { type: string; id: EntityId; }[]' is not assignable to type 'GetResultDescriptionFn<"Post", EntityState<Post>, void, FetchBaseQueryError, {} | undefined>'.
Type '{ type: string; id: EntityId; }[]' is not assignable to type 'readonly TagDescription<"Post">[]'.
Type '{ type: string; id: EntityId; }' is not assignable to type 'TagDescription<"Post">'.
Type '{ type: string; id: EntityId; }' is not assignable to type 'FullTagDescription<"Post">'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"Post"'.ts(2322)
endpointDefinitions.d.ts(188, 5): The expected type comes from property 'providesTags' which is declared here on type 'Omit<EndpointDefinitionWithQuery<void, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, {}>, EntityState<Post>> & { ...; } & { ...; } & QueryExtraOptions<...>, "type"> | Omit<...>'
如果我仅返回
result.ids.map((id) => ({ type: POST_TAG, id }))
或仅返回
[{ type: POST_TAG, id: 'LIST' }]
,则可以正常工作。
- 我该如何输入?
-
此外,不确定当结果为
undefined
时我该怎么办。我应该返回[{ type: POST_TAG, id: 'LIST' }]
吗?
1个回答
这在 typeping provideTag/invalidatesTags 中进行了描述。
定义
POST_TAG
时,您将需要几个
as const
断言。
因此,不是
const POST_TAG = "foo"
,而是
const POST_TAG = "foo" as const
应该可以解决问题。否则它将被输入为“string”,而不是“foo”。
phry
2022-06-06