How to make TypeScript complain about string conca

2020-03-30 02:46发布

Why even in strict mode TypeScript is not complaining about this

function test(firstName: string, lastName?: string): string {
    return firstName + " " + lastName;
}

test('John');

Nor about this

const str: string = '';
const num: object = {};

const result: string = str + num;

I don't remember cases when I would want to get and print on the screen 'John undefined' or '[object Object]'. Is the whole point of type checking is supposed to be catching such errors? (Flow does it)

3条回答
Lonely孤独者°
2楼-- · 2020-03-30 03:09

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

查看更多
爷、活的狠高调
3楼-- · 2020-03-30 03:15

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.

查看更多
▲ chillily
4楼-- · 2020-03-30 03:22

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.

查看更多
登录 后发表回答