0
const a: string = "abc";
const b: string[] = ["def", "ghi"];
const c = a + b

produces abcdef,ghi comma separated string of items in string[]. How to let typescript know this should not be allowed in first place?

opensourcegeek
  • 5,552
  • 7
  • 43
  • 64

1 Answers1

1

c = a + b is actually {} + \[\]

{} + []

The {} here is not parsed as an object, but instead as an empty block (§12.1, at least as long as you're not forcing that statement to be an expression, but more about that later). The return value of empty blocks is empty, so the result of that statement is the same as +[]. The unary + operator (§11.4.6) returns ToNumber(ToPrimitive(operand)). As we already know, ToPrimitive([]) is the empty string, and according to §9.3.1, ToNumber("") is 0.

a is string which is {} side and b (string[]) is []. When you sum string object with array of string, javascript implicitly converts array of string to concatenated string (Which is expected behavior)

so, there is nothing illegal to javascript here.

Community
  • 1
  • 1
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72