Add element to typescript Record<>
Asked Answered
C

2

23

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);
Chloramphenicol answered 1/2, 2021 at 21:35 Comment(1)
What does "without success" mean?Tragicomedy
C
26

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
Corsetti answered 23/4, 2021 at 9:34 Comment(0)
O
1

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

Olatha answered 2/2, 2021 at 1:50 Comment(1)
Cannot read properties of undefined (reading 'add').Scull

© 2022 - 2024 — McMap. All rights reserved.