TypeScript: no error when using `+` operator on incompatible types

Bug Report

today i was shocked to learn that something like 1 + "2", one of the most common examples of why javascript is unsafe, doesn’t cause an error in typescript.

i get that it technically works at runtime, but so does 1 + undefined which correctly causes an error

related: #30239

🔎 Search Terms

concatenate incompatible types operator

(i’d be very surprised if this hasn’t been raised before, but i couldn’t find an existing issue no matter what search terms i used)

🕗 Version & Regression Information

4.7.0-dev.20220504

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.7.0-dev.20220504#code/IwAg1CBEBMlA

💻 Code

1 + "2"

🙁 Actual behavior

no error

🙂 Expected behavior

error when using + operator on incompatible types

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 4
  • Comments: 20 (11 by maintainers)

Most upvoted comments

kotlin

1 + "2" // error
"1" + 2 // no error

Kotlin moment

imo you would typically use string interpolation for cases like that. the languages i’m used to seem to make the same assumption.

python (mypy)

1 + "2" # error
f"{1}2" # no error

dart

void main() {
  1 + "2"; // error
  "${1}2"; // no error
}

kotlin

fun main() {
    1 + "2" // error
    "${1}2" // no error
}