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.


Rate this lesson

Previous lesson Next lesson

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

About the 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...