简体   繁体   English

如何停止与打字稿中的字符串数组串联的字符串

[英]How to stop string concatenated with array of strings in typescript

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

produces abcdef,ghi comma separated string of items in string[]. 产生abcdef,ghi逗号分隔的string []字符串。 How to let typescript know this should not be allowed in first place? 如何让打字稿首先知道这是不允许的?

c = a + b is actually {} + \\[\\] c = a + b实际上是{} + \\[\\]

{} + [] {} + []

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). 这里的{}不会被解析为一个对象,而是被解析为一个空块(第12.1节,至少只要您不强迫该语句为表达式,但稍后再介绍)。 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)). 一元+运算符(第11.4.6节)返回ToNumber(ToPrimitive(operand))。 As we already know, ToPrimitive([]) is the empty string, and according to §9.3.1, ToNumber("") is 0. 众所周知,ToPrimitive([])是空字符串,根据§9.3.1,ToNumber(“”)为0。

a is string which is {} side and b ( string[] ) is [] . a是{}边的string[] ,b( string[] )是[] When you sum string object with array of string, javascript implicitly converts array of string to concatenated string (Which is expected behavior) 当您将字符串对象与字符串数组求和时,javascript会将字符串数组隐式转换为级联字符串(这是预期的行为)

so, there is nothing illegal to javascript here. 因此,这里的javascript没有违法行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM