Author: Dawid Adach
You could ask — what if I don't know what kind of value my variable will have?
- Let's flush our function code and type ine the following:
- Hover over the
myVardeclaration, what do you see?
- What is actually type of the variable
myVar? Let's check it:
- Now let's add an explicit type, cast after the var declaration:
let myVar; myVar = 1; //number myVar = true; //boolean myVar = 'mdb'; //string
The TypeScript compiler doesn't complain. Why!?
TypeScript allows you to use a special type
any. It allows you to use dynamic typing but importantly — it requires 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, the compiler will show two errors regarding the second, and third assignments
We used already four 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 already covered you can also create arrays of different types including the
any type. There is also one more type of variable —
enum but we will cover it in the future.
Previous lesson Next lesson
Spread the word:
Install MDB CLI
It's the fastest way to create and host MDB projects