Introduction
In this article will learn the basic types - any & object type in detail. By functionality we will see the differences between them as well.
What is Any?
- Typescript is static type checking.
- User is not aware about the data type; then user can use any type.
- User can assign any datatype value to the variable, which is intitialized later.
- User can use any keyword to declare the datatype at the time of variable declaration.
- Suppose our function resturns a value which depends on condition & we are assigning this value to a variable; then we can define that the variable has any type.
Example
In the below example first we will declare a variable having type any. We will check the type of variable in the fucntion getValue() & according to that will return a string value from function.
- let myVariable: any;
-
- function getValue(myVariable): string {
- if (typeof(myVariable) === "number") {
- return "Variable is of number type & value is: " + myVariable;
- } else if (typeof(myVariable) === "string") {
- return "Variable is of string type & value is: " + myVariable;
- } else if (typeof(myVariable) == "boolean") {
- return "Variable is of boolean type & value is: " + myVariable;
- } else {
- return "Not able to trace the type of variable & value is: " + myVariable;
- }
- }
- console.log(getValue(5));
- console.log(getValue("Hello!!!"));
- console.log(getValue(true));
- let myArray: number[] = [10, 20, 30, , 40];
- console.log(getValue(myArray));
Output
Execute the code & you will get output like,
- Variable is of number type & value is: 5
- Variable is of string type & value is: Hello!!!
- Variable is of boolean type & value is: true
- Not able to trace the type of variable & value is: 10,20,30,,40
What is Object?
- Object refers to the JavaScript object type.
- It is non-primitive type.
- Object appears to be a more specific declaration than any.
- Every object has a life & user can access the only members inside that objects.
- It may contains properties & functions.
Example
Consider the below example, as we have declared the two variables; i.e., first has any type & second has object. We wiill access the methods from both the variables.
- let a: any;
- let b: Object;
- console.log(a.method());
- console.log(b.method());
Example
Consider the below example variable is declare as object & we are accessing the properties & method from that.
- let myObject: object;
- myObject = {
- a: 10,
- b: 20,
- getAddition: function(): number {
- return this.a + this.b;
- }
- };
- console.log("Function call & addition is: " + myObject.getAddition());
Output
Execute the code & we will get output like:
Function call & addition is: 30
Summary
In this article, you learned basic types - any & object in TypeScript.