I'm currently facing a challenge with TypeScript as I attempt to develop a function that properly assigns default values for an optional object within another object.
Even though I am setting up everything in the parameters, I keep encountering an error indicating that one of the properties (options.target.value) might be undefined. This particular object can either be provided optionally when the function is called and must adhere to an interface requiring the property, or it will be assigned using a function that also follows the same interface if not provided.
What's perplexing is that despite supplying a default options.target, TypeScript isn't satisfied; however, if I check !options.target and provide it through the getTarget() function, TypeScript behaves just fine. Could this be a bug in TypeScript, or am I misinterpreting how default object properties should be configured?
Thank you!
function getTarget(): Target {
const target: Target = page.targets[0];
console.log('target._id = ', target._id); //always OK, TS does not mark this as possibly undefined.
return target;
}
function test(
options: {target?: Target;} //when provided, must have a 'value' property
= {target: getTarget()} //if not provided, default always has a 'value' property
) {
if (!options.target) { options.target = getTarget(); } //without this, I get the TS error below
console.log('options.target', options.target); //always OK
console.log('options.target', options.target.value); //ERROR: TS2532 Object is possibly 'undefined' if required line above commented out
}