Consider the following code example:
const isDisabled: {reason: string} | false = false;
const disabledReason: string = isDisabled?.reason || '';
The the JavaScript code is perfectly valid and it works in runtime, but with typescript you get this error: "Property 'reason' does not exist on type 'false | { reason: string; }'"
Is there a way to make typescript allow this but interpret "reason" as undefined for the case that the property doesn't exist? (Which is the runtime behavior of JavaScript). I expect the resolved type to be string | undefined
, and the compilation to pass.
CodePudding user response:
Your code fails for two reasons:
Because you assign
false
in the statement above, typescript infers thatisDisabled
is alwaysfalse
. If you hoverisDisabled
in the second statement you will seeisDisabled: false
.isDisabled?.reason
doesn't specify thatreason
exists on the object, you first have to cancel out the possibility of it beingfalse
by using:
const disabledReason: string = isDisabled ? isDisabled?.reason : '';
And in complete: (function used because typescript will always infer that isDisabled
=== false otherwise)
const isDisabled: {reason: string} | false = false;
const isDisabledWithReason: {reason: string} | false = { reason: 'Aborted' };
function getDisabledReason(a_isDisabled: {reason: string} | false): string {
return a_isDisabled != false ? a_isDisabled.reason : '';
}
console.log(getDisabledReason(isDisabled)); // ""
console.log(getDisabledReason(isDisabledWithReason)); // "Aborted"
CodePudding user response:
Just be a little more verbose:
const disabledReason: string = isDisabled ? isDisabled.reason : '';