Author: Dawid Adach
You could ask - what if I don't know what kind value my variable will get?
- Let's flush our function code and type following:
- Hover over
myVardeclaration, what do you see?
- What is actually type of variable
myVar? Let's check it:
- Now let's add explicit type cast after var declaration:
let myVar; myVar = 1; //number myVar = true; //boolean myVar = 'mdb'; //string
TypeScript compiler doesn't complain. Why!?
TypeScript allows you to use special type
any. It allows you use dynamic typing but again - it require from you to use it consciously.
myVar = 1; //number console.log(typeof(myVar)); myVar = true; //boolean console.log(typeof(myVar)); myVar = 'mdb'; //string console.log(typeof(myVar));
let myVar: number;
Immediately, compiler will show 2 errors regarding second, and third assignment
We used already 4 different types of variables (
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.
Spread the word: