Open In App

How to Type Dynamic Object with Methods with Dynamic Argument Count ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are going to learn about how to type dynamic objects with methods with dynamic argument count. Type dynamic object with methods with dynamic argument count means defining an object in a programming language such as TypeScript or Python, where the methods of the object can accept varying numbers of arguments dynamically at runtime, providing flexibility in function invocation and parameterization.

Approach 1: Using Function type

In this approach we are using the Function type in TypeScript allows defining dynamic objects with methods accepting variable arguments. The function type represents any function. It can be used to define methods on objects that accept a variable number of arguments.

Syntax:

interface DynamicObject { method: Function; }

Example: The MyObject interface defines a method that accepts a variable number of arguments, and its type is defined as a Function. The obj object conforms to this interface,

Javascript




interface MyObject {
    [methodName: string]: Function;
}
const obj: MyObject = {
    method: function (...args: any[]) {
        console.log("result :", args);
    }
};
obj.method("Geeks", "for", "Geeks");


Output:

result : [ 'Geeks', 'for', 'Geeks' ]

Approach 2: Using a generic function type

In this approach, we are using a generic function type that allows defining dynamic objects with methods accepting variable arguments. A generic function type in TypeScript is a function type definition that can accept different types of arguments, allowing for flexibility and reusability in function declarations.

Syntax:

interface DynamicObject { method: (...args: any[]) => void; }

Example: The myObject interface defines a single property method, which is a function that accepts a variable number of arguments (…args: any[]). The obj object conforms to this interface.

Javascript




interface myObject {
    method: (...args: any[]) => void;
}
 
const obj: myObject = {
    method: function (...args: any[]) {
        console.log("Result:", args);
    }
};
 
obj.method(1, "Two", 3, "four");


Output:

Result: [ 1, 'Two', 3, 'four' ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads