Skip to content

Weird infer by const modifier in spread arguments #53686

Closed
@danni-boii

Description

@danni-boii

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.

Playground link to the class version of the issue

Activity

RyanCavanaugh

RyanCavanaugh commented on Apr 6, 2023

@RyanCavanaugh
Member

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

typescript-bot commented on Apr 8, 2023

@typescript-bot
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @RyanCavanaugh@typescript-bot@danni-boii

        Issue actions

          Weird infer by const modifier in spread arguments · Issue #53686 · microsoft/TypeScript