Here is a function that I've been working on:
function findFirstValid(...values: any) {
for (let value of values) {
if (!!value) {
return value;
}
}
return undefined;
}
This function aims to retrieve the first non-undefined value from the list of arguments passed to it.
However, I encountered an issue when trying to add types to it. I wanted the function to have a dynamic union type based on the argument types supplied to it.
For example:
const item1: string = "Welcome!";
const item2: number;
const item3: boolean = true;
// The expected return type should be: string | number | boolean | undefined
findFirstValid(item1, item2, item3);
I attempted to implement this feature:
function findFirstValid<T extends any>(...values: T[]): T | undefined {
for (let value of values) {
if (!!value) {
return value;
}
}
return undefined;
}
Unfortunately, this approach restricts the function to only accept arguments of the same type.
const item1: string = "Welcome!";
const item2: number;
const item3: boolean = true;
// This will result in an error since item2 and item3 are not strings
findFirstValid(item1, item2);
Is there a way to achieve the desired behavior without restricting the function to a single type?