Bitpath

Lesson 1 · Unit 02

Generics

Type parameters, constraints and defaults

13 exercisesabout 3 min

What you practise

  • A type parameter inferred from the argument, constraints with extends, defaults, generic interfaces, when a generic is not needed

Try a question from this lesson

Pick one

Python would run this and crash on the last line. TypeScript checks before running. With these annotations, what happens?

TypeScript
function first(xs: any[]): any {
  return xs[0];
}
const n = first([1, 2, 3]);
console.log(n.toUpperCase());

The ideas

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

Concept

Type parameters

A type parameter is a variable that stands for a type. first<T> says: an array of some T goes in, one T comes out.

You almost never write the T at the call. The compiler infers it from the argument, so first([1, 2]) returns a number.

Python spells the same idea TypeVar, or def first[T](xs: list[T]) -> T in newer versions.

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

Concept

Generic types

Types take parameters too. Array<number> is the long way to write number[], and Map<string, number>, Set<string> and Promise<User> work the same way, like Python's list[int] and dict[str, int].

Write your own with interface Box<T> or type Box<T>. A parameter may have a default, used when you leave it out.

TypeScript
interface Box<T> {
  value: T;
}
const a: Box<number> = { value: 1 };
const m = new Map<string, number>();
m.set("tea", 3);

interface Page<T = string> {
  items: T[];
}
const p: Page = { items: ["x"] };

10 more exercises in the app

  • 4× multiple choice
  • 2× type the answer
  • 2× fill the blanks
  • 1× true or false
  • 1× order the lines

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