Bitpath

Lesson 2 · Unit 07

Generics

Code that works for any type and still knows which one it got

13 exercisesabout 3 min

What you practise

  • A function that works for any type and keeps track of which, generic types, constraints with extends, keyof, the utility types Partial, Pick and Record

Try a question from this lesson

Pick one

T is a placeholder for a type. The compiler fills it in at each call, from the argument. What does this print?

TypeScript
function first<T>(xs: T[]): T {
  return xs[0];
}
const a = first([4, 5, 6]);
const b = first(["x", "y"]);
console.log(a + 1, b.toUpperCase());

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A type parameter

<T> after the function name declares a type parameter: a name for "whatever type the caller uses".

Wherever T appears, it is the same type. So (xs: T[]): T says: give me a list of something, and I return one of that same something. You have used generic types already: Record<string, number> is one.

TypeScript
function last<T>(xs: T[]): T {
  return xs[xs.length - 1];
}
const n = last([1, 2, 3]);  // a number
const s = last(["a", "b"]); // a string

console.log(n, s); // 3 b

Concept

Constraints

Inside a generic function the compiler knows nothing about T: it could be a number, and numbers have no length.

T extends HasLength limits the choice: any type will do, as long as it has a numeric length. In exchange the body may use it. Strings and arrays both qualify.

TypeScript
type HasLength = { length: number };

function longer<T extends HasLength>(
  a: T, b: T,
): T {
  return a.length >= b.length ? a : b;
}
console.log(longer("hi", "hello"));
// hello
console.log(longer([1, 2], [3]).length);
// 2

Concept

Types made from types

The utility types are generic types that come with TypeScript. Each builds a new type from one you have, so the two can never drift apart.

Change User, and Draft and Card follow by themselves.

TypeScript
type User = {
  id: number; name: string; email: string;
};

type Draft = Partial<User>;
// every property optional

type Card = Pick<User, "id" | "name">;
// only those two properties

type Scores = Record<string, number>;
// any text key, number values

9 more exercises in the app

  • 2× multiple choice
  • 2× fill the blanks
  • 3× type the answer
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy