Typescript any explanation with example

How to use any in TypeScript:

any is a way to opt-out of type checking in typescript. If you want to remove the compile-time check, you can use any. Using any, you are just saying to the compiler that you know what the type for this variable is and you don’t need any type checking.

For example, if you are dependent on a third party service and it returns different types of data, you can use use any for your function parameter. Other logical part you can move inside the function.

Example :

Consider the below example :

let myVar: any;

myVar = "hello";
console.log(typeof (myVar));

myVar = 20;
console.log(typeof (myVar));

myVar = true;
console.log(typeof (myVar));

It has one variable myVar of type any. At first, we are assigning it a string value, one number and one boolean. If you run this program, it will print the below output :

string
number
boolean

So, the type of that any variable is different on each step and we can assign any type of value to it.

It’s equivalent javascript code is :

var myVar;
myVar = "hello";
console.log(typeof (myVar));
myVar = 20;
console.log(typeof (myVar));
myVar = true;
console.log(typeof (myVar));

Simple, plain old javascript.

Using any with an array :

We can also use any array i.e. if we are not sure about the types of array elements, we can use one any array i.e. an array with different types of elements. For example :

let myArr: any[] = [];

myArr.push(1);
myArr.push("one");
myArr.push(true);
myArr.push(3.1415);

console.log(myArr);

It will print :

[ 1, 'one', true, 3.1415 ]

Good thing is you can keep any type of data in an array of type any. And the bad thing is you don’t know what type of data it is when you are popping out.

Using class objects :

We can store any class object in a variable of type any. For example :

class PrintMessage {
    print() {
        return "Hello World !!";
    }
}

class DonotPrintMessage {
}

const obj: any = new PrintMessage();
console.log(obj.print());

const secondObj: any = new DonotPrintMessage();
console.log(secondObj.print());

Explanation :

  • We have two classes here : PrintMessage and DonotPrintMessage. The PrintMessage class contains one method called print that returns one ‘Hello World’ message.
  • DonotPrintMessage doesn’t have any class method.
  • We have created two variables obj and secondObj of type any. obj holds one object of the class PrintMesssage and secondObj holds one object of the class DonotPrintMessage.
  • We are calling the print method on both of these variables. Since both are any variable, the typescript compiler will not verify if the method exists or not. It will allow you to run the progaram,

It will throw one error :

TypeError: secondObj.print is not a function

You might also like: