1

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. So in my question, TypeScript assigned the default type of Y as number[][] which does not convey that every inner-array element will have minimum two elements. Stating the type of Y explicitly assert that restriction. Now, we cannot append, say an empty inner array to Y later in the code. That gives the required guarantee to the compiler to stop complaining.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.