What are the differences between any vs Object in TypeScript?

In this shot, we will go through the differences of two data types, any and Object.

any

Syntax

var variablename:any;
  • TypeScript provides us with the data type any to use when we don’t know the type of data that the variable holds while writing code.
  • It may be the case that you are getting data from server, and you are not sure about data type of variable. If so, use any.
var data:any;
  • Or, if you are not sure which user might enter the data into this variable, then use any.
var inputFromUser:any

Example

In the following code snippet, we created a variable data with type any, and then we assign the string Data from server to data.

// creating variable with any data type
var data:any;
//assigning string to data
data = "Data from server"
//priting data to console
console.log(data)

We can re-assign different values of different data types to variable data.

// creating variable with any data type
var data:any;
//assigning string to data
data = "Data from server"
//priting data to console
console.log(data)
//reassigned with integer
data = 10
console.log(data)
//reassigned with boolean
data = true
console.log(data)

Object

Syntax

var a: Object
  • TypeScript provides the datatype Object to store plain JavaScript objects.
  • Object contains key-value pairs separated by a comma ,.
{
    1:"apple",
    2:"Banana"
}

Example

In the following example, we are creating a variable fruits with data type as Object, and assigning values to it in line 5.

//creating variable fruits of data type Object
var fruits:Object;
//assigning object to fruits
fruits = {
1:"Apple",
2:"Banana",
3:"Orange"
}
//pritintg fruits Object
console.log(fruits)

We can access the values present in the Object with keys.

//creating variable fruits of data type Object
var fruits:Object;
//assigning object to fruits
fruits = {
1:"Apple",
2:"Banana",
3:"Orange"
}
//get value for key 1
console.log(fruits["1"])

Free Resources