我试图定义一个具有两个泛型的类型,并基于泛型描述一个具有特定类型参数的函数,但是可以推断出返回类型。
案例:
export type StoreAction<ActionTypes extends string, State> = <R = any>(
dispatch: Dispatch<Action<ActionTypes>>,
state: State,
) => R;
用法:
const fetchCountries = (): StoreAction<Action, DetailsData> => async dispatch => {
const countries = await getCountries();
dispatch({
type: Action.initState,
payload: countries.data,
});
};
有关异步功能(StoreAction
)的消息:
Type '<R = any>(dispatch: Dispatch<Action<Action>>) => Promise<void>' is not assignable to type 'StoreAction<Action, DetailsData>'. Type 'Promise<void>' is not assignable to type 'R'.
在示例中,TypeScript编译器表示无法将number
分配给泛型。有什么建议可以正确执行,以便可以推断出此类型的函数的返回类型?