Typescript - Tips & Tricks - infer keyword

Today I talk about the infer keyword. Sometimes, we need to get the value type of an array or get the...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 18 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #17 Previous
    Conditional Type
  2. #18 Reading now
    infer keyword
  3. #19 Up next
    Mapped Types
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof
  4. #4 Union and Intersection
  5. #5 Overloaded Functions
  6. #6 this parameter
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword Current
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

Today I talk about the infer keyword. Sometimes, we need to get the value type of an array or get the return type of a function. To do this I need to introduce the infer keyword. To explain this feature I show you an example

type UnboxingArray<T> = T extends Array<infer Member> ? Member : T;

type UnboxingArrayString = UnboxingArray<string[]>; // string
type UnboxingArrayNumber = UnboxingArray<number[]>; // number
type UnboxingString = UnboxingArray<string>; // string

As you can see, in the UnboxingArray type, we can detect if the T type extends an array and if so we can infer the element type or else we return the T type. As a demonstration, if you see the type of the UnboxingArrayString and the UnboxingArrayNumber you can note how the UnboxingArray infers the string and the number type. In contrast, in the UnboxingString, the UnboxingArray can’t infer the type of the elements because the type doesn’t extend an array so it returns the string type. Now I show you the infer keyword applied to the function result.

type ReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;
function getPerson() {
  return {
    name: "name",
    surname: "surnmae",
  };
}
type Person = ReturnType<typeof getPerson>;
/**
type Person = {
  name: string;
  surname: string;
}
*/
type StringResult = ReturnType<string>; // never

In this example, you can note that if the T type extends a function, the ReturnType infers the type of the function result otherwise it returns the never type. To demonstrate it, you can see how the Person type is composed of a name and a surname fields on the contrary the StringResult is of the never type.

Great news for us, the ReturnType is already included inside of the Typescript types.

It’s all guys. Bye bye

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.