【问题标题】:In TypeScript, how do i type a function's arguments but not the return value?在 TypeScript 中,我如何输入函数的参数而不是返回值?
【发布时间】:2019-03-19 15:29:42
【问题描述】:

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

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

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

上面的分型解决了每次都要手动输入参数的问题,但是需要我手动输入函数的返回值,之前是自动工作的。

有没有办法输入函数的参数,但让 typescript 自动检测函数体的返回值?

【问题讨论】:

    标签: typescript redux redux-thunk reselect


    【解决方案1】:

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

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

    【讨论】:

    • 这解决了我的问题,谢谢!不过,以这种方式更改代码只是为了“让它看起来更适合转译器”仍然感觉很奇怪。
    • 是的 .. 代码风格是一种品味 .. 在这种情况下,我认为无论你用哪种方式编写它都不会造成重大的性能损失,有时 TS 编译器确实需要一些如果我们想让所有相关人员更轻松,请提供帮助;)
    猜你喜欢
    • 2021-05-03
    • 2019-06-07
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多