How to declare a function argument that can accept any type in TypeScript

3 Answers

0 votes
function AcceptAnyType(x: any): void {
    console.log(`The type of x is: ${typeof x}`);
}
 
AcceptAnyType(384);      
AcceptAnyType("ABCD");   
AcceptAnyType(3.14);   
AcceptAnyType([1, 2, 3]); 
AcceptAnyType(new Date());
AcceptAnyType({});
 
 
 
/*
run:
 
"The type of x is: number" 
"The type of x is: string" 
"The type of x is: number" 
"The type of x is: object" 
"The type of x is: object" 
"The type of x is: object"
 
*/

 



answered Jul 31, 2025 by avibootz
0 votes
function AcceptAnyType(x: any): void {
    if (typeof x === "string") {
        console.log("x is a string");
    } else if (typeof x === "number") {
        console.log("x is a number");
    } else if (Array.isArray(x)) {
        console.log("x is an array");
    } else {
        console.log("x is of another type");
    }
}
 
AcceptAnyType(384);      
AcceptAnyType("ABCD");   
AcceptAnyType(3.14);   
AcceptAnyType([1, 2, 3]); 
AcceptAnyType(new Date());
AcceptAnyType({});
 
 
 
/*
run:
 
"x is a number" 
"x is a string" 
"x is a number" 
"x is an array" 
"x is of another type" 
"x is of another type" 
 
*/

 



answered Jul 31, 2025 by avibootz
0 votes
function AcceptAnyType(x: any): void {
    if (x instanceof Date) {
        console.log("x is a Date object");
    } else if (x instanceof Array) {
        console.log("x is an Array");
    } else if (x instanceof Object) {
        console.log("x is an Object");
    } else {
        console.log("x is not an object");
    }
}
 
AcceptAnyType(384);      
AcceptAnyType("ABCD");   
AcceptAnyType(3.14);   
AcceptAnyType([1, 2, 3]); 
AcceptAnyType(new Date());
AcceptAnyType({});
 
 
 
/*
run:
 
"x is not an object" 
"x is not an object" 
"x is not an object" 
"x is an Array" 
"x is a Date object" 
"x is an Object" 
 
*/

 



answered Jul 31, 2025 by avibootz
...