Can anyone clarify TypeScript behavior in this scenario?
JavaScript
const test1 = [ ['a', 'b'], ['c', 'd'], ]; const test2 = [ ...[ ['a', 'b'], ['c', 'd'], ], ]; console.log(JSON.stringify(test1) === JSON.stringify(test2));
The output will be
true
since the arrays are identical.TypeScript
const test1: [string, string][] = [ ['a', 'b'], ['c', 'd'], ]; const test2: [string, string][] = [ ...[ ['a', 'b'], ['c', 'd'], ], ];
However, with TypeScript, an error occurs on
test2
:Type 'string[][]' is not assignable to type '[string, string][]'. Type 'string[]' is not assignable to type '[string, string]'. Target requires 2 element(s) but source may have fewer.
You can view a reproducer on TypeScript Playground.
Is there a way to make this work without resorting to complicated type casting?
UPDATE
Here's a more specific example of what I'm trying to achieve:
const someValues = [1, 2, 3];
const test3: [string, string][] = [
...someValues.map(value => ['some string', 'another string']),
];
UPDATE #2
Following Алексей Мартинкевич's advice, I found that this solution works:
const someValues = [1, 2, 3];
const test3: (readonly [string, string])[] = [
...someValues.map(i => ['a', 'a'] as const),
];
Is there a simpler and clearer approach for my colleagues and my future self to understand?
(avoiding confusion down the road :D)