After reviewing other responses, it seems that the issue may lie in how Typescript statically analyzes the code. If anyone can provide further explanation, that would be greatly appreciated.
Below is my code. I am unable to see how it could result in being undefined. While you can call foo({})
or foo({ algorithm: undefined })
, it will still be merged with default
and the resulting object will always contain 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();