在 TypeScript 中,如何键入函数的参数而不是 return 值?

In TypeScript, how do i type a function's arguments but not the return value?

我在 TypeScript 中使用 redux、redux-thunk 和 reselect 编写应用程序。

在很多地方,我是这样写函数的:

const selectThing = (store: IStore) => store.path.to.thing;

const fetchThing = (thingId: string) => (dispatch: Dispatch<IStore>, getState: () => IStore) => {
  // fetch a thing by id and handle the result

  return result;
}

特别是在第二个示例中,第二个函数的输入注释占用了很多space,我想编写一个函数接口来处理输入参数。

type StoreSelector<T = any> = (store: IStore) => T;
type ThunkDispatch<T = any> = (dispatch: Dispatch<IStore>, getState: () => IStore) => T;

上面的输入解决了每次都必须手动输入参数的问题,但是它们需要我手动输入函数的 return 值,之前它是自动工作的。

有没有办法输入函数的参数,然后让 typescript 自动检测函数体的 return 值?

您可以使用函数来推断 return 类型和参数类型。

function createThunkDispatch<T>(fn: (dispatch: Dispatch<IStore>, getState: () => IStore) => T) {
    return fn;
} 

// const fetchThing: (thingId: string) => (dispatch: Dispatch<IStore>, getState: () => IStore) => string
const fetchThing = (thingId: string) => createThunkDispatch((dispatch, getState) => {
    // fetch a thing by id and handle the result

    return "result";
});