Description
Bug Report
The const modifier does not behave as expected. Typescript would warn me to infer the const generic parameters when I use the spread argument in a function when the literal type object consists of 2 different primitive literals.
And I am not sure whether this type of behaviour is intentional.
🔎 Search Terms
const modifier, typescript5, spread syntax, spread argument
🕗 Version & Regression Information
This behaviour begins starting at typescript 5.0 (where the const modifier is introduced)
I have been seeing this behaviour between typescript 5.0 to the nightly build of 5.1
⏯ Playground Link
Playground link with relevant code
💻 Code
type A = 1 | '2';
function concat<const U>(...items: (A | U)[]) {
return [...items];
}
const originalArray: A[] = [1, '2'];
const perfectConcatenatedArray = concat(...originalArray, 3, 4 ,5);
const okayConcatenatedArray = concat(...originalArray, '3', '4', '5');
const concatnatedArray = concat(...originalArray, 3, 4, 5, '6', '7');
🙁 Actual behaviour
Typescript is inferring that the const U
should be 3
instead of 3 | 4 | 5 | '6' | '7'
It prompts an error stating that Number 4
is not assignable to the parameter of type A | 3
for concatnatedArray
.
While both perfectConcatenatedArray
and okayConcatenatedArray
are perfectly fine
🙂 Expected behaviour
I would expect concatnatedArray to have type 1 | '2' | 3 | 4 | 5 | '6' | '7'
.
It is possible to do so if I wrote it in a class manner and chain the concat function. But I cannot do it within the same concat function.
Activity
RyanCavanaugh commentedon Apr 6, 2023
Inference will infer that it's OK to form a union of types from the same primitive literal family, but not different ones. See also
#32596 (comment)
typescript-bot commentedon Apr 8, 2023
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.