I have the following function definitions
function getX1(): string | undefined { ... }
function getX2(): string { ... }
function myFunc(x: string | undefined): MyClass | undefined {
if (x === undefined) return undefined;
return { ... };
}
function consume(val: MyClass) { ... }
myFunc is guaranteed to only return undefined if x is undefined.
Scenario 1:
const x1: string | undefined = getX1();
const res1 = myFunc(x1);
if (res1) {
consume(res1);
}
Here, I want the caller to make sure the result res1 is not undefined before continuing.
Scenario 2:
const x2: string = getX2();
const res2 = myFunc(x2);
consume(res2);
Here, I don't want to add the same overhead for the caller. This snippet currently gives me a compiler error. I can't figure out how to avoid the undefined check without using !. Is there a way to have typescript enforce this rule for me?
string | undefined, getX2 returnsstring. I've added this clarification above.