In this lesson, you read the angle brackets in the types of the club’s per-species counts, its year list and an async function, and wrote them yourself for a map and a set that start empty.
Key Points
- A generic type names a kind of value, then what it holds. The club’s counts are a
Map, and the checker showsMap<string, number>.Mapis the kind of value. The types inside the angle brackets are type arguments:stringis the type of every key, andnumberis the type of every value. Like a function’s arguments, they fill in the details, but they’re types, and only the checker uses them. - The type arguments flow into the methods.
counts.get("Red Kite")isnumber | undefined. The.get()method takes a key of the key type,string, and returns the value type,number, orundefined, because a map may not hold the key you ask for. - A set takes one type argument. The year list is a
Set<string>. ASetholds values without keys, so its one type argument is the type of each item. - Read nested types from the outside in.
newSpecies()is an async function, and its return type isPromise<string[]>. The outer layer is a promise. If it fulfills, it gives you astring[], an array of strings that holds the species names.Array<string>is the same type asstring[], spelled as a generic. This course writes the square brackets. - Fill in the type arguments when a collection starts empty. With nothing to infer from,
new Map()isMap<any, any>, so nothing you put in it or read from it gets checked. An emptynew Set()isSet<unknown>, which accepts any value you add.npm run checkstays clean all the same, even in strict mode, so nothing warns you. Writenew Map<string, number>()andnew Set<string>(). When you create a collection with values, let the checker infer its types. - Type arguments are erased with the other types. Node.js creates an ordinary map and set, and fills them as usual.
Final Code
Here’s yearlist.ts at the end of the lesson. counts and yearList start empty with their type arguments written, and newSpecies() is a cut-down version of a lookup that will wait on the species API. The file is a toy for reading types. kites and newSpecies() stay for their hovers, and the run doesn’t use them: