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
anyto 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 typevar data:any;//assigning string to datadata = "Data from server"//priting data to consoleconsole.log(data)
We can re-assign different values of different data types to variable data.
// creating variable with any data typevar data:any;//assigning string to datadata = "Data from server"//priting data to consoleconsole.log(data)//reassigned with integerdata = 10console.log(data)//reassigned with booleandata = trueconsole.log(data)
Object
Syntax
var a: Object
- TypeScript provides the datatype
Objectto store plain JavaScript objects. - Object contains
key-valuepairs 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 Objectvar fruits:Object;//assigning object to fruitsfruits = {1:"Apple",2:"Banana",3:"Orange"}//pritintg fruits Objectconsole.log(fruits)
We can access the values present in the Object with keys.
//creating variable fruits of data type Objectvar fruits:Object;//assigning object to fruitsfruits = {1:"Apple",2:"Banana",3:"Orange"}//get value for key 1console.log(fruits["1"])