Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 577
Klimashkin Avatar asked Nov 01 '18 05:11

Klimashkin


People also ask

Can you use a double in string concatenation?

The “+” operator with a String acts as a concatenation operator. Whenever you add a String value to a double using the “+” operator, both values are concatenated resulting a String object. In-fact adding a double value to String is the easiest way to convert a double value to Strings.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

How do you concatenate strings in TypeScript?

The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string. Syntax: string. concat(string2, string3[, ..., stringN]);


1 Answers

As MartinJohns said on a github issue regarding this topic

I think this would belong more to the realm of linters. This is not really a type error, it's just undesired behavior.

no-base-to-string

restrict-plus-operands

restrict-template-expressions

no-implicit-coercion

like image 159
Juanjo Martinez Avatar answered Oct 20 '22 19:10

Juanjo Martinez