当我在 Typescript 中创建新的 Redux Store 时,我在添加属性时遇到问题:
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
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 = ...
这被称为声明合并/模块扩充 https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation.
您还需要设置您的tsconfig.json
从中读取类型@types
目录。添加"typeRoots": [ "./@types", "./node_modules/@types" ]
到这个文件(注意:这些是相对于你的baseDir
,因此进行相应修改。
另请注意您正在您的类型和您编写的代码之间创建一个契约。如果您未能正确设置中间件,sagaTask
将Required
在类型上但是undefined
事实上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)