Infer the Return Type of a Generic Function Type Parameter

Share this video with your friends

Send Tweet

When working with conditionals types, within the “extends” expression, we can use the “infer” keyword to either get the type of the elements of an array, or even to get the return type of a function. We can use this to build a “FnReturnType<T>” type, that will give us the return type of the function passed in as the generic parameter.

Prem Prakash
Prem Prakash
~ 6 years ago

Raes what could the use case for such an advanced thing? A few examples will be really helpful.

Rares Matei
Rares Matei(instructor)
~ 5 years ago

Hi Prem! One use case would be the example Yellow Tiger gave on my other lesson: inferring the action types from your redux action creators:

https://egghead.io/lessons/redux-automatically-infer-typescript-types-in-switch-statements

export function messagesFetchRequested(messageId: string) {
  return {
    type: actionTypes.MESSAGES_FETCH_REQUESTED,
    payload: messageId
  };
}

type Action = ReturnType<typeof messagesFetchRequested>

//action type will automatically be inferred to be:

type Action = {
    type: string;
    payload: string;
}