I'm trying to understand how to properly approach handling an unknown variable, which may be an object with certain properties I can use. This derives from a variety of try/catch scenarios when working with a third party library which is still in development, so "e" may or may not be an object with certain properties.
Below is a simplified version of my question, but there are other manifestations of the issue. Therefore, I wish to avoid type assertions or disable type checking. What I'm looking for is a proper way to check an "unknown" value to see if it is an object with certain properties.
Why is the following if condition insufficient? TypeScript just views it as an unknown object and isn't use the info I've passed to ensure (1) it is an object, (2) it is not null, and (3) it has the key "errNum".
What other possible condition could cause "console.log(e.errNum)" to throw an error at runtime after all of these checks? This fails both in the VSCode GUI and when building with webpack 5 (using eslint after recent migration from tslint). I can't think of any other edge cases that would cause problems at runtime.
try {
const err = { errNum: 12 };
throw err;
} catch (e) {
// e is inferred as unknown, as it should be
if (e && typeof e === 'object' && 'errNum' in e) console.log(e.errNum); // TS error: Property 'errNum' does not exist on type 'object'.
}