如何键入异步 thunk 的调度?
How to type dispatch of an async thunk?
我目前正在使用 reduxjs/toolkit,但我无法将钩子输入到 return 异步 thunk 的调度。这是我在 https://redux-toolkit.js.org/usage/usage-with-typescript 之后的设置(不是完整的功能代码):
// thunk.ts
export const callThunk: AsyncThunk<
ResponseBody,
void,
{state: RootState}
> = createAsyncThunk(
'someAsyncThunkAction',
async (_data, {rejectWithValue}) => {
const response = await someAPICall();
if (!response.ok) {
return rejectWithValue(`Put failed: ${response.status}`);
} else {
return await response.json();
}
);
// store.ts
export const store = configureStore({reducer: rootReducer});
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
// hook.ts
import {callThunk} from './thunk'
import {useAppDispatch} from './store'
type HookProperties = {
onCallThunk: () => // <--- this is the type that I haven't figured out
};
export const useHook = (): HookProperties => {
const appDispatch = useAppDispatch();
return {
onCallThunk: () => appDispatch(callThunk())
};
};
希望我可以在我的组件中调用这个钩子,如下所示:
import {useHook} from './hook'
const {onCallThunk} = useHook();
onCallThunk().then(/* do something here */)
onCallThunk
的类型在 hook.ts
中应该是什么?
你最好的选择是:你希望使用的部分,比如
type HookProperties = {
onCallThunk: () => void // for example if you don't care about the result being used
};
或者,简单地说:将 : HookProperties
注释放在一边并保留它。 TypeScript 比您自己编写的更了解 return 类型,手动写下它不会有任何好处 - 除了稍后在您更改某些内容时进行更多维护。
我目前正在使用 reduxjs/toolkit,但我无法将钩子输入到 return 异步 thunk 的调度。这是我在 https://redux-toolkit.js.org/usage/usage-with-typescript 之后的设置(不是完整的功能代码):
// thunk.ts
export const callThunk: AsyncThunk<
ResponseBody,
void,
{state: RootState}
> = createAsyncThunk(
'someAsyncThunkAction',
async (_data, {rejectWithValue}) => {
const response = await someAPICall();
if (!response.ok) {
return rejectWithValue(`Put failed: ${response.status}`);
} else {
return await response.json();
}
);
// store.ts
export const store = configureStore({reducer: rootReducer});
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
// hook.ts
import {callThunk} from './thunk'
import {useAppDispatch} from './store'
type HookProperties = {
onCallThunk: () => // <--- this is the type that I haven't figured out
};
export const useHook = (): HookProperties => {
const appDispatch = useAppDispatch();
return {
onCallThunk: () => appDispatch(callThunk())
};
};
希望我可以在我的组件中调用这个钩子,如下所示:
import {useHook} from './hook'
const {onCallThunk} = useHook();
onCallThunk().then(/* do something here */)
onCallThunk
的类型在 hook.ts
中应该是什么?
你最好的选择是:你希望使用的部分,比如
type HookProperties = {
onCallThunk: () => void // for example if you don't care about the result being used
};
或者,简单地说:将 : HookProperties
注释放在一边并保留它。 TypeScript 比您自己编写的更了解 return 类型,手动写下它不会有任何好处 - 除了稍后在您更改某些内容时进行更多维护。