Open In App

TypeScript any Type

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, any type is a dynamic type that can represent values of any data type. It allows for flexible typing but sacrifices type safety, as it lacks compile-time type checking, making it less recommended in strongly typed TypeScript code. It allows developers to specify types for variables, function parameters, and return values, enhancing code quality and maintainability. However, there are situations where you may encounter dynamic or untyped data, or when working with existing JavaScript code. In such cases, TypeScript provides the ‘any’ type as a flexible solution.

Syntax

let variableName: any = value;

Where,

  • let: It is used to declare a variable.
  • variableName: It is the name of the variable you are declaring.
  • ‘: any’: It specifies that the variable can hold values of any type.
  • value‘: It is the initial value assigned to the variable, which can be of any type.

There are several methods that can be used to perform TypeScript any Type, which are listed below:

We will explore all the above methods along with their basic implementation with the help of examples.

Explicitly Declare a Variable as ‘any’

Declare a variable as ‘any’ in TypeScript by explicitly defining its type, allowing it to hold values of any type, making it dynamically flexible but potentially less type-safe.

Example: In this example, A variable, ‘Inp,’ initially declared as ‘any’ with the value “GEEKSFORGEEKS,” is later reassigned to [1, 2, 3]. TypeScript permits this dynamic type change due to the ‘any’ type. The console displays the updated [1, 2, 3] value.

Javascript




// TypeScript
  
let Inp: any = "GEEKSFORGEEKS";
Inp = [1, 2, 3];
console.log(Inp);


Output:

[ 1, 2, 3 ]

Function parameters and Return type with ‘any’ type

Function parameters and return type with ‘any’ type means using TypeScript’s ‘any’ type for function arguments and return values, making the function accept and return values of any type, sacrificing type checking.

Example: In this example, we define a generic function GeekFunc that accepts and returns any type. It demonstrates using the function with various types, accompanied by type annotations for clarity and type safety.

Javascript




function GeekFunc<T>(arg: T): T {
    return arg;
}
  
const strout: string = 
    GeekFunc("GEEKSFORGEEKS");
const boolout: boolean = GeekFunc(true);
const intout: number = GeekFunc(21);
const keyout: { key: string } = 
    GeekFunc({ key: "GeeksforGeeks" });
  
console.log(strout);
console.log(intout);
console.log(boolout);
console.log(keyout);


Output:

GEEKSFORGEEKS
21
true
{ key: 'GeeksforGeeks' }

‘Any’ type with Array

TypeScript’s ‘any’ type with arrays, allows diverse data types within the array. While this provides flexibility, it lacks type safety and static type checking, potentially leading to runtime errors.

Example: In this example, we initialize myArray as an any[], allowing diverse data types. It employs the push method to insert an integer, boolean, and object. TypeScript’s flexibility permits this mix. The code concludes by displaying myArray in the console.

Javascript




// TypeScript
  
let myArray: any[] = [];
  
myArray.push(200);
myArray.push(false);
myArray.push({ key: "GEEKSFORGEEKS" });
  
console.log(myArray);


Output:

[ 200, false, { key: 'GEEKSFORGEEKS' } ]

Object with Dynamic Properties

In this approach, TypeScript to create objects with dynamic properties, allowing flexibility in adding and accessing properties without a predefined structure.

Example: In this example, we define an object oB with dynamic properties, initially containing various data types. It then dynamically adds rating and email properties and logs the object to the console.

Javascript




// TypeScript
  
let oB: { [key: string]: any } = {
    name: "GEEKSFORGEEKS",
    age: 15,
    isActive: true,
    Desire: ["Content Writing", "Contest", "Potd"],
    address: {
        street: "Sector-136",
        city: "Noida",
        State: "Uttar Pradesh"
    },
};
  
oB.rating = 4.5;
oB.email = "support@geeksforgeeks.org";
  
console.log(oB);


Output:

{
name: 'GEEKSFORGEEKS',
age: 15,
isActive: true,
Desire: [ 'Content Writing', 'Contest', 'Potd' ],
address: { street: 'Sector-136', city: 'Noida', State: 'Uttar Pradesh' },
rating: 4.5,
email: 'support@geeksforgeeks.org'
}

Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads