Ahmed Sbai
Ahmed Sbai

Reputation: 16169

Why 'X' + Y = 'XY' in TypeScript ? Expect an error

I am trying to understand TypeScript and how it works so this is a very simple example :

const X: string = '5';
const Y: number = 6;
console.log(X+Y) // output '56' ! why not an error ? and why not 11 ?

With JavaScript, such a result is acceptable, but since TypeScript is designed to avoid logic errors, why it does not mind if we try to append a "string" to a "number". Logically speaking, this makes no sense even for concatenation. also why the default procedure is to treat Y as string and concatenate why not try to convert X to number and add ?

Upvotes: 2

Views: 130

Answers (1)

ruakh
ruakh

Reputation: 183211

One of the tenets of TypeScript is that "your existing working JavaScript code is also TypeScript code" [link].

There's plenty of existing JavaScript code with bits like this:

const x = '5';
const y = 6;
console.log(x + y); // '56'

and that do expect the behavior of JavaScript. It would be a significant barrier to migration if TypeScript forced developers to change the above. (And it's a nonstarter to suggest that it should output 11; we couldn't trust TypeScript if renaming a file from .js to .ts could introduce bugs detectable only at runtime.)

Now, you might want to object that your code is different, in that you explicitly annotate the variables with their types. But TypeScript provides type inference, and it would be a horrible mess if

const x : string = '5';

produced a variable with slightly different behavior than

const x = '5';

Language design always involves tradeoffs, and TypeScript has decided that some JavaScript quirks are worth keeping for compatibility.

Upvotes: 5

Related Questions