skip to Main Content

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);

1

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


  1. It’s not considered an error. TypeScript respects JavaScript’s implicit value conversion with the various operators (+, -, etc.). From a type perspective doing someString + someNumber is valid, and results in a value of type string. The number is implicitly converted to string and then the strings are concatenated. Even the various strict options will allow that implicit conversion.

    Even strictly-typed languages like Java and C# allow implicitly converting numbers to strings when performing + operations.

    Login or Signup to reply.
  2. This is valid JavaScript. When using the += operator in combination with a String, JavaScript converts each value to a String. So you can see it like

    a = a + String(b)
    a = 'Hello' + '10'
    

    Therefore you do not change to type of a

    Login or Signup to reply.
  3. 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 as string

    let a :string = "Hello";
    let b :number = 10
    

    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 will a = hello10 that is string.

    it will give error if you do

    b += a;
    

    because here type of b will changed to string that is not valid in typescript.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search