TypeScript Generic Function Arguments Based on Type Key/Value(type)

TypeScript Generic Function Arguments Based on Type Key/Value(type)

When working with TypeScript, it is common to come across scenarios where you need to define a function that accepts arguments based on a specific type key/value. In this blog post, we will explore different solutions to this problem.

Solution 1: Using Conditional Types

One way to achieve this is by using conditional types. Conditional types allow you to create types that depend on a condition. Here’s an example:

type Args = T extends 'string' ? [string] :
               T extends 'number' ? [number] :
               T extends 'boolean' ? [boolean] :
               never;

function myFunction>(type: T, ...args: Args): void {
    // Function implementation
}

In this example, we define a generic type Args that maps different types to their corresponding argument types. The myFunction function takes a type parameter T which is constrained to be a key of Args. This ensures that the type argument passed to the function is valid.

Here’s how you can use this function:

myFunction('string', 'Hello'); // Valid
myFunction('number', 42); // Valid
myFunction('boolean', true); // Valid
myFunction('string', 42); // Error: Argument of type '42' is not assignable to parameter of type 'string'

Solution 2: Using Function Overloads

Another approach is to use function overloads. Function overloads allow you to define multiple function signatures for the same function. Here’s an example:

function myFunction(type: 'string', arg: string): void;
function myFunction(type: 'number', arg: number): void;
function myFunction(type: 'boolean', arg: boolean): void;
function myFunction(type: string, arg: any): void {
    // Function implementation
}

In this example, we define three function overloads for the myFunction function, each with a specific type and argument. The last function signature is the implementation signature, which takes a generic type and arg of any type.

Here’s how you can use this function:

myFunction('string', 'Hello'); // Valid
myFunction('number', 42); // Valid
myFunction('boolean', true); // Valid
myFunction('string', 42); // Error: Argument of type '42' is not assignable to parameter of type 'string'

Both solutions provide a way to define a function that accepts arguments based on a specific type key/value. Choose the solution that best fits your needs and coding style.

Happy coding!


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *