Static vs dynamic typing

let's replace the content of the onStartup

  1. First, let's replace the content of the onStartup function:
  2. onStartup(){
                    let test = 'mdb';
                    test = 5;
                    }

    You will see that TypeScript complains about the second assignment of test:

    ERROR in src/app/app.component.ts(18,3): error TS2322: Type '5' is not assignable to type 'string'.

    This code would work perfectly fine in JavaScript which allows dynamic change of types. You might think, that this approach is better, however, although it might look easier for a developer it is not. Imagine that there you are working on a project with a team of developers and one of them by mistake changes the type of your variable from number to string. All logic based on that variable will be broken now (as it would be comparing a variable to a number).

  3. Let's now surround number 5 with quotes: '5'
  4. test = '5';

    This time the compiler won't complain because we have cast our 5 from a number to a string. As a result we can assign it to our variable, however, we have to remember that it will be treated as a string and not a number.

  5. Let's try another test, copy the following condition into your code, but before you paste it think for a moment and try to guess what will be the output:
  6. if (test === 5){
      console.log('equals');
    } else {
      console.log('not equals');
    }

    Once you paste the following condition into your code, TypeScript generates an error:

    ERROR in src/app/app.component.ts(20,5): error TS2365: Operator '===' cannot be applied to types 'string' and 'number'.

    Once again, this condition would execute in plain JavaScript and could lead us to an error. By looking at the code you might think that result of the comparison will be true, but due to different types, it would evaluate to false. TypeScript protects you from making such mistakes warning that you are trying to compare different types.