异步配置时导出 Redux 存储状态类型

Export Redux store state type when configuring it asynchronously

各位!

我正在尝试使用预加载状态配置 Redux 存储,我只能使用 TypeScript 异步获取它。

问题

我是否能够像官方描述的那样延迟推断状态和分派类型 doc,而当计算 preloadedState 时,我仅在 Promise 回调中接收存储实例?

这是一堆代码,希望能阐明我的意图:

const getPreloadedState = async (): Promise<RootState> => { // Need RootState type on that very stage already
    const restoredSession = await Session.restore()
    const preloadedState: RootState = {
        session: {
            sessionKey: restoredSession.sessionKey,
            expiresIn: restoredSession.expiresIn
        }
    }
    return Promise.resolve(preloadedState)
}

export const configureStoreAsync = async (): Promise<EnhancedStore> => {
    const preloadedState = await getPreloadedState()
    const store = configureStore({
        reducer: rootReducer,
        preloadedState: preloadedState
    })

    //  Unable to export this types here when state is ready. 
    //  (getting "Modifiers cannot appear here" error)
    //  export type RootState = ReturnType<typeof store.getState>
    //  export type AppDispatch = typeof store.dispatch

    return Promise.resolve(store)
}
可能的解决方案

这是我想出的:

//  Generate dummy store to calculate typeof state
const store = configureStore({reducer: rootReducer})    
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

但我对该领域更有知识的开发人员的意见非常感兴趣..


提前致谢!

// remove the return type from this function or you will actually erase imporant type information
export const configureStoreAsync = async () => {
    const preloadedState = await getPreloadedState()
    const store = configureStore({
        reducer: rootReducer,
        preloadedState: preloadedState
    })
    
    // the Promise.resolve is unneccessary, that is implied by using an `async` function

    return store
}


type Store = Awaited<ReturnType<configureStoreAsync>>
export type RootState = ReturnType<Store['getState']>
export type AppDispatch = Store['dispatch']