Skip to content

Treat + on string literal types the same way as string templatesΒ #44905

Closed

Description

@Nixinova

Bug Report

πŸ”Ž Search Terms

string concatenation types, template literal type

⏯ Playground Link

Playground

πŸ’» Code

type Letter = 'A' | 'B';
type Num = '1' | '2';
type Label = `${Letter}${Num}`;

let letter: Letter = 'A'; // type='A'
let num: Num = '1'; // type='1'
let label1: Label = `${letter}${num}`; // does work, type="A1" | "A2" | "B1" | "B2"
let label2_inferred = letter + num // type = string (!!)
let label2: Label = letter + num; // doesn't work

πŸ™ Actual behavior

label2 gives Error: Type 'string' is not assignable to type '"A1" | "A2" | "B1" | "B2"'.
It should not be a string type as both Letter and Num are clearly defined values.

πŸ™‚ Expected behavior

label2 and label1 should be identical.

Template literals and string concatenation should act identical when joining strings.

πŸ•— Version & Regression Information

  • This changed between versions 4.2.3 and 4.3.5
    • Both label1 and label2 are invalid in 4.2, only label2 is in 4.3 / 4.4alpha.

Other info

Activity

  1. changed the title [-]Template literal values are treated differently from string concatenation[/-] [+]Treat `+` on string literal types the same way as string templates[/+] on Jul 6, 2021
  2. ahejlsberg commented on Jul 7, 2021

    @ahejlsberg
    Member

    We've discussed this before and, as I recall, concluded support for + on literal types would have to also extend to numeric literal types. Which in turn would bring -, *, / and possibly other operators into play. It wasn't clear where we'd stop. Another issue that concerned us is the quadratic nature of resolving the type operators applied to unions. For example, + on two unions each of 100 literal types produces a union of as many as 10,000 literal types. This is true of template literals as well of course, but those don't look quite as innocent.

  3. Nixinova commented on Jul 7, 2021

    @Nixinova
    Author

    Maybe add a note to the error message then (if new type is string)? "If the more specific type is required, use a template string instead" with a quick fix attached.

  4. Nixinova commented on Jul 22, 2021

    @Nixinova
    Author

    Anyway closing per ahejlsberg's comment

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

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions