Lesson 1 · Unit 02
Generics
Type parameters, constraints and defaults
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?
function first(xs: any[]): any {
return xs[0];
}
const n = first([1, 2, 3]);
console.log(n.toUpperCase());Correct answer
Compiles, crashes at run time
Why
any in, any out: the compiler has forgotten that the list held numbers, so it lets .toUpperCase() through and the program dies at run time. The function needs a way to say "whatever type comes in is the type that goes out".
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.
function first<T>(xs: T[]): T {
return xs[0];
}
const n = first([1, 2, 3]); // number
const s = first(["a", "b"]); // stringConcept
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.
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.