Reputation: 2243
Is it possible to initialize the ReadOnlyMap
with values generated during runtime in TypeScript? The Map
can be initialized if the array is provided as part of constructing the Map
, but fails if the array is passed to it by means of a variable. Please see the code below.
// Works.
let X: ReadonlyMap<number, number> = new Map([
[0, 0],
[1, 1],
]);
let Y = [
[0, 0],
[1, 1],
];
// Does not work.
// Argument of type 'number[][]' is not assignable to parameter of type 'ReadonlyArray<[number, number]>'.
// Type 'number[]' is missing the following properties from type '[number, number]': 0, 1
let Z: ReadonlyMap<number, number> = new Map(Y);
Is there another way available to construct the Map
in a single statement? I will like to avoid newing up an empty Map
, call set()
for each value and then copying its reference to ReadonlyMap
.
Upvotes: 1
Views: 5317
Reputation: 1430
Have you tried explicit typing of your input array? For example:
const Y: ReadonlyArray<[number, number]> = [
[0, 0],
[1, 1],
];
const Z: ReadonlyMap<number, number> = new Map<number, number>(Y);
Upvotes: 1