Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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
...