Reputation: 13
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?
Upvotes: 1
Views: 89
Reputation: 249536
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";
});
Upvotes: 2