'How to enforce generic parameter to allow undefined

I would like to use a wrapper for different API requests where I don't always know what the response will be and I don't know whether the request will be successful. I would like to be able to specify the expected return type of my function in a few cases without making it mandatory so my first attempt was

function fetch<T=any>(){
let body:T = undefined
// fetch the request
return body
}

Obviously the compiler will mark body here with

'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.

so next I tried to do

function fetch<T extends any|undefined = any>(){
let body:T = undefined
// fetch the request
return body
}

but this gives me the error:

'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.

Now I am out of ideas and I am not sure what the right language is to describe the problem and google it. If somebody could point me in the right direction, that would be highly appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source