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