Adding Properties To Created Redux Store In Typescript
Solution 1:
@types/
| - redux.d.ts
src/
| ...
| ... store.ts
in redux.d.ts
import * as Redux from "redux"
declare module "redux" {
export interface Store {
sagaTask: ... // provide the types for `store.sagaTask` here
}
}
in store.ts
const store = createStore(...)
store.sagaTask = ...
this is known as declaration merging / module augmentation.
You need to also setup your tsconfig.json
to read types from this @types
dir. Add "typeRoots": [ "./@types", "./node_modules/@types" ]
to this file (note: these are relative to your baseDir
, so modify accordingly.
Also note that you're creating a contract between your types and the code you write. If you fail to setup your middleware properly, sagaTask
will be Required
in types but undefined
in reality.
Solution 2:
I haven't used Saga so I'm not sure about best practices or what ramifications this approach might have, but the issue is that the Store type doesn't have a sagaTask, so TypeScript won't let this happen. The easiest way that I can see to solve this is to extend Store and add a sagaTask field, then copy the old store to a new object of the extended type.
The downside to this is that you could easily run into a situation where a function is expecting an object with a Store type, so it won't accept this new object.
Are you sure this needs to be a property of the store, or can you just run sagaMiddleware.run(rootSaga)?
Post a Comment for "Adding Properties To Created Redux Store In Typescript"