Issue
I'm trying to assign a Boolean value that by default is equal to true but can be conditional depending on whether the actual Boolean Value exists in a props object or not, like this
// default boolean to true
let valid:boolean = true;
if(self.props.hasOwnProperty("valid")) {
// a property has been specified so use that instead
valid = self.props.valid;
}
self.props.valid is an optional parameter but I am getting the following error :
TS2322: Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.
How can I get the conditional assignment to work?
Solution
Because it's optional, its value may be undefined, which you can't assign to a boolean variable. hasOwnProperty won't help because optional properties are allowed to be present with the value undefined.
You can use a different type guard:
if (self.props.valid !== undefined) { // Or `if (typeof self.props.valid !== "udnefined"`
valid = self.props.valid;
}
Or you could use nullish coalescing:
valid = self.props.valid ?? valid;
That only changes the value if self.props.valid isn't undefined.
You could even do that when defining valid originally:
let valid:boolean = self.props.valid ?? true;
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.