A stricter return type for a function with an optional fallbackValue parameter
04:30 02 Dec 2025

I wrote a function that allows safe execution of another function and returns a default value in case of an error.

function safeExecute(operation: () => T, fallbackValue?: T | undefined): T | undefined {
    try {
        return operation();
    } catch (error) {
        return fallbackValue;
    }
}

The fallbackValue parameter is optional. Therefore, the value returned by the safeExecute function has a type T | undefined. That's actually the question. I want the function to return `T` if the fallbackValue is set, and T | undefined if it is not set. So


safeExecute(() => 42, 0) -> number
safeExecute(()=> "foobar") -> string | undefined

How I can achieve this? I tried using generic type for fallbackValue but no luck.

typescript typescript-generics