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?

2
  • I don't think you can avoid that. This is how JavaScript works with the + operator. Note that the type for c is the expected one though string. Commented Jan 18, 2019 at 11:55
  • when is your expected output? "abcdefghi", ["abc, "def", "ghi"] or some sort of error? Commented Jan 18, 2019 at 11:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.