Lesson 1 of 10

Generics

Goal

The return type follows the input type

01

Explanation

Say you have a function that returns the first element of an array. What type does it return? If you write any, you lose everything types give you, because the compiler no longer knows that the first element of a string[] is a string.

Generics make the type itself a parameter you pass to the function, like this: function first<T>(xs: T[]): T | undefined. Pass an array of strings and T automatically becomes string. Pass numbers and it becomes number.

The | undefined isn't there for decoration. An empty array has no first element, and this type makes whoever calls the function deal with that case.

02

Your task

Make first a generic function, so the type it returns follows the type of the array you pass it.

Checks

6 checks
  1. No type errors
  2. Returns the first element
  3. An empty array returns undefined
  4. With an array of strings, the result is a string
  5. The result isn't treated as a number
  6. The result may be undefined, so it can't be assigned to a plain string
03

Hints

0/3
Track lessons0 of 10 done

Learn generics, discriminated unions and utility types, and see how the type system becomes a tool for designing your program.

Advanced level, 10 lessons, 2 hours in total.

main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Learn generics, discriminated unions and utility types, and see how the type system becomes a tool for designing your program.

Advanced level, 10 lessons, 2 hours in total.