Static vs dynamic typing in typescript

Author: Dawid Adach

-

Static vs dynamic typing

  1. Replace content of onStartup function:
  2. onStartup(){
    let test = 'mdb';
    test = 5;
    }  

    You will see that TypeScript complains about 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 type of your variable from number to string. All logic based on that variable will be broken now (i.e. comparing a variable to a number).

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

    This time compiler won't complain because we have cast our 5 from number to 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 make 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 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 could 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.


Next lesson

Spread the word:
Do you need help?: Use our support forum

About author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...