Typescript variable types

Author: Dawid Adach

-

Type: any

You could ask - what if I don't know what kind value my variable will get?

  1. Let's flush our function code and type following:
  2.   let myVar;
    
      myVar = 1;      //number
      myVar = true;   //boolean
      myVar = 'mdb';  //string
    

    TypeScript compiler doesn't complain. Why!?

  3. Hover over myVar declaration, what do you see?
  4. Any type

    TypeScript allows you to use special type any. It allows you use dynamic typing but again - it require from you to use it consciously.

  5. What is actually type of variable myVar? Let's check it:
  6.   myVar = 1;     //number
      console.log(typeof(myVar));
      myVar = true;  //boolean
      console.log(typeof(myVar));
      myVar = 'mdb'; //string
      console.log(typeof(myVar));
    

    The output:

    Dynamic type
  7. Now let's add explicit type cast after var declaration:
  8.   let myVar: number;

    Immediately, compiler will show 2 errors regarding second, and third assignment

    Error

Other types:

We used already 4 different types of variables (number, string, boolean and any. Are there any others? Yes, there are.

  let a: number;                    //numeric type
  let b: string;                    //string 
  let c: boolean;                   //true or false
  let d: any;                       //any (dynamic)
  let e: number[] = [1,2,3];        //array of numbers
  let f: string[] = ['a','b','c'];  //array of strings
  let g: any[] = [true, 1, 'a'];    //array of any 
  

As you can see except for basic types which we covered you can also create arrays of different types including any type. There is also one more type of variable - enum but we will cover it in a future.


Next lesson

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

About author

Dawid Adach
For more than 5 years Dawid was working as an IT Consultant specializing in SOA/EAI/ESB for banking domain. He was gaining experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the biggest companies within a domain. Since 2 years as a co-founder of mdbootstrap.com & brandflow.net is using and teaching others technologies like Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...