Looking for a solution:
function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) {
let result : string;
if (!firstOptionalVariable && !secondOptionalVariable) {
throw new Error('both are undefined');
}
result = firstOptionalVariable ? firstOptionalVariable : secondOptionalVariable;
};
Check out the code in this playground: https://tsplay.dev/mxJoxw.
The two variables can be either strings or undefined. The first "if" statement ensures that at least one of them is a non-empty string. So, why does TypeScript give an error stating
Type 'string | undefined' is not assignable to type 'string'
? What would be the correct approach to solve this issue?