Here is the function I currently have, but unfortunately I encountered the following error:
Type '(T & undefined) | { obj: T & ({} | null); }' is not assignable to type 'T extends undefined ? undefined : { obj: T; }'. Type 'T & undefined' is not assignable to type 'T extends undefined ? undefined : { obj: T; }'.(2322)
function undefinedOrObject<T>( param: T ): T extends undefined ? undefined: {obj: T} {
return typeof param === 'undefined' ? param : { obj: param }
}
param
can be of type number, boolean or undefined. If it's undefined, I simply want to return undefined. For any other primitive type, I would like to return an object like {obj: param}
. My goal is to achieve this without using any casting with as ...
. Do you have any suggestions on how to approach this?