Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptWhat are the differences between any vs Object in TypeScript?

What are the differences between any vs Object in TypeScript?

TypeScript is an open-source programming language. It is a superset of JavaScript language. TypeScript is designed for the development of large applications.

any: It is a built-in data type in TypeScript which helps in describing the type of variable which we are unsure of while writing the code.
Though the data type ‘any’ is useful it shouldn’t be used unnecessarily.

  • Syntax:
    var x: any; // This means x has no interface.
    
  • Features:
    • This data type can be used when there are no type definitions available.
    • The ‘any’ datatype can be used to denote any JavaScript value.
  • Examples: Below codes illustrates any datatype in TypeScript:
    • Code 1:




      <script>
      function add(one: any, two: any): number {
        return one + two;
      }
          
      console.log(add('Geeks', 'forneveropen'));     
             
      </script>                    

      
      
    • Output:
      Geeksforneveropen
    • Code 2:




      <script>
      function subtract(one: any, two: any): number {
        return one - two;
      }
         
      console.log(subtract(9, 5)); 
      </script>

      
      
    • Output:
      4

Object: It describes the functionality, object helps in representing the non-primitive types that is everything except number, string, boolean, big int, symbol, undefined and null. In TypeScript Object(O uppercased) is different from object(o lowercased).

  • Syntax:
    var y: Object; // This means y has Object interface.
    
  • Features:
    • Object exposes the functions and properties defined within the Object class.
    • The object is a more specific way of declaration.
  • Examples: Below codes illustrates object in TypeScript:
    • Code 1:




      <script>  
          Student={roll_no:11,name:"XYZ"}  
          document.write(Student.roll_no+" "+Student.name+" ");  
      </script>

      
      
    • Output:
      11 XYZ
    • Code 2:




      <script>  
          emp={id:102,name:"ABC",salary:10000}  
          document.write(emp.id+" "+emp.name+" "+emp.salary);  
      </script> 

      
      
    • Output:
      102 ABC 10000

Difference between any and Object in TypeScript:

any Object
If you employ ‘any’ to a nomethod() function you are basically telling the transpiler that no information will be provided regarding what’s stored in it. Therefore the transpiler doesn’t restrict anything and it transpiles fine. The Object class doesn’t have a nomethod() function, therefore the transpiler will generate a miscalculation.
any is way more flexible to use than Object. Object is way more specific in declaration than any.
any does not ignore any compile time checks . Objects take more time to compile.

RELATED ARTICLES

Most Popular

Recent Comments