Reading through other answers it may be how Typescript statically analyses the code, if that is the case if someone is able to explain further that'd be great.
Here is my code, I can't see how it could be undefined, yes you may call foo({})
or foo({ algorithm: undefined })
but it'd be then merged with default
and the resulting object would always have algorithm
type Options = {
algorithm?: string;
identifier?: string;
}
const defaults: Options = {
algorithm: 'sha256',
identifier: 'Fizz',
}
function foo(options: Options = defaults) {
options = { ...defaults, ...options };
if (!(options.algorithm in someOtherObj)) { // Object is possibly 'undefined'.
}
if (Object.prototype.hasOwnProperty.call(someOtherObj, options.algorithm)) {
/**
Argument of type 'string | undefined' is not assignable to parameter of type 'PropertyKey'.
Type 'undefined' is not assignable to type 'PropertyKey'.
**/
}
if (someOtherObj[options.algorithm]) { // Type 'undefined' cannot be used as an index type.
}
}
foo();