I am able to call a method on the return value of a function with | undefined in the return type, which I didn't think would be possible.
I have a helper function with the following signature:
export const as_trait = <T extends keyof Traits>(o_: object, symbol: T): Traits[T] | undefined => { ... }
At the very top of the function I even have this guard clause:
if ( ! o_.hasOwnProperty(symbol) ) {
return undefined;
}
Traits is an interface type. The idea is I have several modules that may add symbols to this interface that map to certain types.
Here's what confuses me: I can call as_trait, pass it a value of type any for the o_ parameter, and then call a method on the return value of as_trait without ever checking if it's undefined.
i.e. this compiles:
const whatever = this.context[entry.key];
const initable = as_trait(whatever, TInitable);
// if ( initable === undefined ) continue;
await initable.init();
Why does this happen? Can I get typescript to enforce the undefined check as I expected it to?
I'm not interested in "why do you want to do this?" or "just do it my way instead". I want to understand this problem that I find myself in.