How to use Type Guards In Javascript
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.
Example: In this example The function infers return types based on input types: length of a string for strings, and `false` for non-strings, respecting conditional return types.
function getResult<T>(input: T): T extends string ? number : boolean {
if (typeof input === 'string') {
return input.length as T extends string ? number : boolean;
} else {
return false as T extends string ? number : boolean;
}
}
// Test with string input
const result1: number = getResult("hello");
// Test with number input
const result2: boolean = getResult(10);
console.log(result1);
console.log(result2);
Output:
5
false
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