I'm new to TypeScript and struggling trying to create a function which properly sets default values for an optional object inside an object.
When I try to define everything in the parameters, I'm getting an error that one of the properties (options.target.value) may be undefined. The object in question may be optionally provided when the function is invoked and constrained to an interface that requires the property, or if the object is not provided will be set using a function which also uses the same interface.
What's confusing is that I'm providing a default options.target that isn't satisfying TypeScript, but when I check !options.target and provide it using the same getTarget() function, TypeScript is happy. Is this just a bug in TypeScript, or am I misunderstanding something about how default object properties are set?
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
}