简体   繁体   中英

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

I am writing an application using redux, redux-thunk and reselect in TypeScript.

In many places, i am writing functions like this:

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

Especially in the second example, the typing annotations for the second function take up much space and i would like to write a function interface which handles typing the arguments.

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

The typings above solve the issue of manually having to type the parameters each time, but they will require me to manually type the return value of the functions, which worked automatically before.

Is there a way to type a function's arguments, but let typescript then automatically detect the return value of the function body?

You can use a function to get inference for the return type and inference for the parameter types.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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