【发布时间】:2019-05-17 06:09:46
【问题描述】:
将接口应用到我的 redux thunk 操作的 dispatch() 函数时,错误检查似乎是错误的。
例如,如果我注释掉一个属性,Typescript 会抱怨实际启用的属性,说它丢失了:
...
type ThunkResult<R> = ThunkAction<R, RootState, undefined, Action>;
export interface ShowSnackbar {
type: string,
isOpened: boolean
}
export const showSnackbar = (): ThunkResult<void> => (dispatch, getState) => {
dispatch<ShowSnackbar>({
// type: 'baz',
isOpened: true // <-- 'isOpened' does not exist in type 'ThunkAction<ShowSnackbar ...
});
}
在检查了 redux-thunk ThunkDispatch 类型后,我注意到重载函数的第一个函数声明被忽略,而当我的操作具有注释掉的属性时调用了第二个函数声明(故意引入错误):
export interface ThunkDispatch<S, E, A extends Action> {
<T extends A>(action: T): T;
<R>(asyncAction: ThunkAction<R, S, E, A>): R;
}
如果说,我删除<R>(asyncAction: ThunkAction<R, S, E, A>): R;,类型检查恢复正常,TS 会正确警告我:
“类型”在类型 '{ isOpened: true; 中丢失}' 但在类型中是必需的 'ShowSnackbar'。
我已经整理了一个 demo on TS Playground 来演示这个问题。
还是我做错了什么?
谢谢!
【问题讨论】:
标签: typescript redux typescript-typings redux-thunk