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

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

Why even in strict mode TypeScript is not complaining about this

相关标签:
3条回答
  • 2020-12-19 20:11

    Create a type-safe variadic function to do concatenation for you.

    concat(...strings: string[]): string {
      var concatenated = "";
      for (var i = 0; i <  strings.length; i++) {
        concatenated += strings[i];
      }
      return concatenated;
    };
    

    Now when you concatenate, use your function:

    const str: string = '';
    const num: object = {};
    
    const result: string = concat(str, num); // throws error
    

    Example here

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 20:19

    Because it is valid to concatenate strings and undefined values. Same issue for your second example. In JavaScript, your can '' + {} (would not be of much use though, typically).

    Strict typing prevents unsafe access like lastName.length in your example.

    0 讨论(0)
提交回复
热议问题