How to make TypeScript complain about string concatenation with other type?

前端 未结 3 1969
孤独总比滥情好
孤独总比滥情好 2020-12-19 19:27

Why even in strict mode TypeScript is not complaining about this

3条回答
  •  借酒劲吻你
    2020-12-19 20:14

    In the context of the + operator, you can't, because it's designed to be able to support mixed types, for example in the expression "Count: " + a.length().

    The conversion of objects to strings can be implied (in + concatenation) and controlled. In modern JavaScript this might be demonstrated as follows:

    let o = {};
    o.toString = ()=> "two"
    alert("one" + " " + o); // Displays "one two"

    So there isn't really a reason to reject the second example just based on types.

    As to the first example, conversion from unknown and null to string are implied and defined in abstract ToString() operation, though I'm not sure it's changeable, it seems well defined. Now, it certainly might be reason to flag with a tool like tslint, but it remains a valid operation in ECMAScript.

提交回复
热议问题