繁体   English   中英

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

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

我正在使用Redux,redux-thunk和在TypeScript中重新选择编写应用程序。

在许多地方,我正在编写如下函数:

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;
}

尤其是在第二个示例中,第二个函数的类型注释会占用很多空间,我想编写一个处理参数类型的函数接口。

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

上面的键入解决了每次都必须手动键入参数的问题,但是它们将要求我手动键入函数的返回值,该函数以前会自动工作。

有没有办法键入函数的参数,但是让Typescript然后自动检测函数体的返回值?

您可以使用函数来获取返回类型的推论和参数类型的推论。

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";
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM