How to use Type Switching In Javascript

Type Switching in TypeScript involves using a switch statement to determine the type of a variable dynamically, enabling conditional behaviour based on types, and facilitating versatile handling of different data types within a function.

Example: In this example, The function `getValue<T>` returns the length of a string input or true for non-strings.

Javascript
function getValue<T>(input: T): T extends string ? number : boolean {
    switch (typeof input) {
        case 'string':
            return (input as unknown as string)
                .length as T extends string ? number : boolean;
        default:
            return input === 0 ? false as T extends string ? number : 
                boolean : true as T extends string ? number : boolean;
    }
}

const result1 = getValue("Geeks");
const result2 = getValue(10);

console.log(result1);
console.log(result2);

Output:

5
true

How to Implement a Generic Function with a Conditional Return Type ?

Implementing a generic function with a conditional return type involves creating a function that can accept multiple data types and return different types based on specified conditions. This allows for flexible behavior depending on inputs. The function’s return type may vary dynamically, enhancing its versatility and utility in handling diverse scenarios within a program or system. There are several ways to implement a generic function with conditional return types which are as follows:

Table of Content

  • Using Conditional Types
  • Using Type Switching
  • Using Type Assertion
  • Using Type Guards:
  • Using Inline Conditional Statements

Similar Reads

Using Conditional Types

In this approach the Conditional types in TypeScript enable dynamic typing based on conditions, allowing the return type of a function to vary depending on the input type or other criteria, enhancing type flexibility and inference....

Using Type Switching

Type Switching in TypeScript involves using a switch statement to determine the type of a variable dynamically, enabling conditional behaviour based on types, and facilitating versatile handling of different data types within a function....

Using Type Assertion

Type assertion involves explicitly specifying the return type of a function, overriding TypeScript’s inference. It’s a manual approach and requires ensuring type safety....

Using Type Guards:

Using type guards, a generic function checks the type of its input. If it matches a condition, it returns a specific type; otherwise, it returns another type, enabling conditional return types....

Using Inline Conditional Statements

Inline conditional statements offer a concise way to implement conditional return types within a generic function. This approach leverages JavaScript’s ternary operator to determine the return type based on specified conditions....