Add element to typescript Record<>

Viewed 17518

I have a Record set up like this: let myRecord = Record<String, Set<String>>

How can I add an element to a set inside the record? I have tried the following without success:

let key = "key";
let stringToAdd = "stringToAdd";
myRecord[key].add(stringToAdd);
2 Answers

You can use the square brackets [] and an assignment to add elements to the record.

let mySet: Set<string> = new Set();
mySet.add("stringToAdd");

let myRecord: Record<string, Set<string>> = {};

myRecord["key"] = mySet;    // <--- Like this

There are two issues here. First you want to use the lowercase string. There is a difference (String is the new-able constructor), but just know that you want the lowercase version for any basic type.

Second you are mixing up types and values when you do let myRecord = Record<String, Set<String>>. You cannot set a variable to a type. You can declare the type of the variable but you also need to set the value.

let myRecord: Record<string, Set<string>> = {};

This creates a variable myRecord whose initial value is an empty object {} and whose type is Record<string, Set<string>>.

Playground Link

Related