I’m new to Typescript, and while trying a very simple script I cannot see the linter (neither the compiler) erroring out the following:
No error detected:
let a: string = 'hello';
let b: number = 10;
a += b;
console.log(a);
I tried changing the tsconfig file and couldn’t make it work. Any tips on where to look?
For references, this is my tsconfig.json
:
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"rootDir": "./src",
"sourceMap": true,
"outDir": "./dist",
"removeComments": true,
"noEmitOnError": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"alwaysStrict": true,
"skipLibCheck": true,
},
}
3
Answers
It’s not considered an error. TypeScript respects JavaScript’s implicit value conversion with the various operators (
+
,-
, etc.). From a type perspective doingsomeString + someNumber
is valid, and results in a value of typestring
. The number is implicitly converted to string and then the strings are concatenated. Even the variousstrict
options will allow that implicit conversion.Even strictly-typed languages like Java and C# allow implicitly converting numbers to strings when performing
+
operations.This is valid JavaScript. When using the
+=
operator in combination with aString
, JavaScript converts each value to aString
. So you can see it likeTherefore you do not change to type of
a
there is not an error, its valid in Ts. it will throw an error if type of a will be changed, but here type of
a
remains same asstring
you are doing
a += b;
that is same as
a = a + b;
but here type of
a
remains sting because+
operator add numbers and strings as well.so
a = "hello" + 10
willa = hello10
that is string.it will give error if you do
because here type of b will changed to string that is not valid in typescript.