Inferring Types within Conditional Types

1. Welcome and Icebreaker:

  • If you could infer any hidden detail from a situation, what would you want to know?

2. Outline the Session:

  • We’ll learn how to use the infer keyword in conditional types to extract types.
  • Learning Outcomes: Understand how to use infer for advanced type manipulation.
  • Let’s infer some types!

3. Concept Explanation:

  • infer Keyword: Used in conditional types to introduce a new type variable to be inferred from another type.
  • Useful for extracting types from tuples, arrays, functions, etc.
  • Syntax:
    type ElementType<T> = T extends (infer U)[] ? U : T;
    

4. Live Coding Demonstration:

type ElementType<T> = T extends (infer U)[] ? U : T;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getName(): string { return "Alice"; }
type NameReturn = ReturnType<typeof getName>; // string

// Inferring from tuple
type First<T> = T extends [infer F, ...any[]] ? F : never;
type FirstOfTuple = First<[number, string, boolean]>; // number

5. Tasks:

  • Short Exercise:
    1. Write a conditional type that infers the element type of an array.
    2. Write a type that infers the return type of a function.
    3. Write a type that infers the first element of a tuple.