

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Object Literal Types
incomplete
2: Extra Properties
incomplete
3: Optional Object Properties
incomplete
4: Empty Object Type
incomplete
5: Discriminated Unions
incomplete
6: Sets
incomplete
7: Maps
incomplete
8: Dynamic Keys
incomplete
9: Dynamic Default Properties
incomplete
10: PropertyKey
incomplete
11: Readonly Modifier
incomplete
12: 'As Const' and Object.freeze
incomplete
13: Satisfies
incomplete
14: Function Overloads
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
TypeScript (obviously) also has a built-in for maps, which are collections of key-value pairs. You can specify the types of the keys and values using type parameters <K, V>.
// A Map with string keys and number values
const podracerSpeeds = new Map<string, number>();
podracerSpeeds.set("Anakin Skywalker", 947);
podracerSpeeds.set("Sebulba", 941);
podracerSpeeds.set("R2-D2", true);
// Error: Argument of type 'true' is not assignable to parameter of type 'number'
podracerSpeeds.set(420, 69);
// Error: Argument of type 'number' is not assignable to parameter of type 'string'
A map is a "set-like" object, and as such uses the size property instead of length.
console.log(podracerSpeeds.size);
// 2
How to easily iterate over a map:
for (const [racer, speed] of podracerSpeeds) {
console.log(`${racer} raced at ${speed} speed`);
}
// Anakin raced at 947 speed
// Sebulba raced at 941 speed
Here's the most important methods of a map, get, delete, and has.
console.log(podracerSpeeds.get("Sebulba"));
// 941
console.log(podracerSpeeds.has("Sebulba"));
// true
podracerSpeeds.delete("Sebulba");
console.log(podracerSpeeds.get("Sebulba"));
// undefined
Let's add file sharing to Support.ai's internal email system.
Complete the getFileLength function. It takes:
Map<string, string> that represents filenames -> fileContentsfilename to get the length ofIt returns the number of bytes in the file's contents. If the filename is not present in the map, return 0.
Use the TextEncoder class and its encode method to encode the file contents (a string) into a Uint8Array, and return the length of the resulting array.