我在 redux 中编写功能组件,并为特定操作添加了返回值。
新值来自 Promise,所以如果类型被称为 Ival
返回值的类型为 Promise<Ival | null>
(如果响应失败则为 null)。
我的问题是如何确定 Ival
的返回类型?
这是 Action :
export const addVal = (data: IData) => async (dispatch: IDispatch): Promise<IVal | null> => {
try {
const resp = await api.vals.create(data);
dispatch({ type: "CREATE_VAL", payload: resp });
return resp;
} catch (error) {
dispatch({ type: "ERROR_MSG" ,payload: error });
return null;
}
};
这是我正在使用的函数:
const createNewConnection = async (data: IData): Promise<void> => {
try {
const newVal: IVal | null = await dispatch(addVal(data));
onValCreated(newVal);
} catch (e) {
onValCreated(null);
}
};
onValCreated
函数接收 IVal
输入参数,这是错误信息:
"TS2559: Type '(dispatch: IDispatch) => Promise ' has no properties in common with type 'IVal'"
我都试过 dispatch 了:
// First try
const newVal: IVal | null = await dispatch<IVal | null>(addVal(data));
// Second try
const newVal: IVal | null = await dispatch<Promise<IVal | null>>(addVal(data));
但是没用
最佳答案
await
关键字基本上是在 JS 中“解压”Promise,等待 Promise<number>
, 会给你一个 number
, 意味着你已经有了正确的方法。但是从它的样子来看,你试图在错误的地方应用这个规则。您不必在调用 时等待,但在处理函数的返回 值时(意味着:将参数传递给onValCreated
而不是dispatch
时) ).但是,错误消息为您提供了调度功能,因为这是您从中获取“错误类型”的地方。
修复很少,只需做这样的事情并用“嵌套”等待“解压”Promise:
const newVal: IVal | null = await dispatch(await addVal(data));
https://stackoverflow.com/questions/63267496/