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

前端 未结 3 1971
孤独总比滥情好
孤独总比滥情好 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

提交回复
热议问题