将属性添加到在 Typescript 中创建的 Redux Store [英] Adding properties to created Redux Store in Typescript
问题描述
我在 Typescript 中创建新的 Redux Store 时在添加属性时遇到问题:
I'm having issues adding a property when I create a new Redux Store in Typescript:
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
return composeWithDevTools(applyMiddleware(...middleware))
}
return applyMiddleware(...middleware)
}
function configureStore (initialState = exampleInitialState) {
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
rootReducer,
initialState,
bindMiddleware([sagaMiddleware])
)
store.sagaTask = sagaMiddleware.run(rootSaga)
return store
}
export default configureStore
带有以下错误消息:
27:9 Property 'sagaTask' does not exist on type 'Store<{ error: any; count: number; lastUpdate: number; light: boolean; placeholderData: any; } | { lastUpdate: any; light: boolean; count: number; error: boolean; placeholderData: any; }, any>'.
25 | )
26 |
> 27 | store.sagaTask = sagaMiddleware.run(rootSaga)
| ^
28 |
29 | return store
30 | }
有什么建议吗?
推荐答案
@types/
| - redux.d.ts
src/
| ...
| ... store.ts
在redux.d.ts
import * as Redux from "redux"
declare module "redux" {
export interface Store {
sagaTask: ... // provide the types for `store.sagaTask` here
}
}
在store.ts
const store = createStore(...)
store.sagaTask = ...
这被称为声明合并/模块扩充一>.
您还需要设置您的 tsconfig.json
以从此 @types
目录读取类型.添加 "typeRoots": [ "./@types", "./node_modules/@types" ]
到这个文件(注意:这些是相对于你的 baseDir
,所以相应修改.
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.
另请注意,您正在创建您的类型和您编写的代码之间的契约.如果你没有正确设置你的中间件,sagaTask
在类型上将是 Required
而在现实中 undefined
.
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.
这篇关于将属性添加到在 Typescript 中创建的 Redux Store的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!