Issue
I'm writing some TypeScript code where I want to add an element to my Map. My Map is of type <number, number[]>
, so when I add a new key-value pair I want to initialize the value to a new empty array.
I know that I can do this:
let arr: number[] = [];
myMap.set(i, arr);
But I would prefer to do this:
myMap.set(i, new number[]);
That is how it's done in C# and I was hoping I could do the same in TypeScript, but I'm having trouble finding how to do it. Perhaps I just have the wrong syntax?
Solution
If your Map
is already typed (eg Map<number, number[]>
), you don't need to type the arguments.
For a Map<K, V>
, the signature for Map.prototype.set()
is
(method) Map<K, V>.set(key: K, value: V): Map<K, V>
You can simply pass an empty array which will implicitly satisfy the number[]
argument type
const myMap: Map<number, number[]> = new Map();
myMap.set(1, []);
Answered By - Phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.