Everyday TypeScript: Sets
Welcome to the Sets lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Recent versions of JavaScript have added a "set" data type. Sets are collections that hold elements, in the same way that arrays do. The main difference is that a set can only contain one copy of any given element.
(If you'd like a refresher on sets, check out the sets lesson in our Modern JavaScript course!)
>
const s = new Set([1, 2, 3]);s.has(1);Result:
>
const s = new Set([1, 2, 3]);s.has(2);Result:
true
>
const s = new Set([1, 2, 3]);s.has(4);Result:
false
We can add elements to existing sets.
>
const s = new Set([1, 2, 3]);s.add(4);s.has(4);Result:
true
When writing TypeScript, sets are a generic type. A
Set<string>can only containstrings.>
let s: Set<string> = new Set(['a', 'b', 'c', 4]);s.has('a');Result:
type error: Type 'Set<string | number>' is not assignable to type 'Set<string>'. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.As usual, we can use any type as a generic type parameter, as long as it type checks. We can fix the type error above by creating a
Set<string | number>.>
let s: Set<string | number> = new Set(['a', 'b', 'c', 4]);s.has('a');Result:
true
TypeScript will stop us from calling methods like
hasoraddwith the wrong type.>
let s: Set<string> = new Set(['a', 'b', 'c']);s.has('a');Result:
true
>
let s: Set<string> = new Set(['a', 'b', 'c']);s.has(1);Result:
type error: Argument of type 'number' is not assignable to parameter of type 'string'.
ArrayandSetare different types. That means thatArray<string>andSet<string>are different too. We can't assign an array to a set or vice-versa.>
let strings: Set<string> = new Set(['a']);let strings2: Array<string> = strings;strings2;Result:
type error: Type 'Set<string>' is missing the following properties from type 'string[]': length, pop, push, concat, and 20 more.
Here's a code problem:
The
setIsEmptyfunction below should decide whether the set is empty. It already has a correct function body that uses.sizeto perform that check. Add the missing type for the function'ssetparameter.Note that the function is generic, so it should work with any type of set:
Set<number>,Set<string>, etc. You'll need to use the type parameterTasSet's type parameter. (But you won't need to change the function's body in any way!)function setIsEmpty<T>(set: Set<T>): boolean {return set.size === 0;}[setIsEmpty(new Set(['a'])),setIsEmpty(new Set([1, 2, 3])),setIsEmpty(new Set([])),];- Goal:
[false, false, true]
- Yours:
[false, false, true]