Home > Blockchain >  Typescript is Unable to Set Conditional Optional Boolean Value
Typescript is Unable to Set Conditional Optional Boolean Value

Time:02-22

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?

CodePudding user response:

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;
}

Playground example

Or you could use nullish coalescing:

valid = self.props.valid ?? valid;

Playground example

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;

Playground example

CodePudding user response:

You defined valid as only a boolean not boolean | undefined

So you either

let valid:boolean | undefined = true;

if(self.props.hasOwnProperty("valid")) {
    valid = self.props.valid; // possible undefined is introduced here
}

or

let valid:boolean = true;

if(self.props.hasOwnProperty("valid")) {
    valid = self.props.valid ?? true // also could be the variable valid
    // this was valid is never undefined    

CodePudding user response:

TS cannot tell the property already exists by looking at the if condition. Tell the compiler that you know the property exists :

let valid:boolean = true;

interface propsInterface {
  valid? : boolean
}

let props : propsInterface = {
  valid : false
}


if(props.hasOwnProperty("valid")) {
    // a property has been specified so use that instead
    valid = props.valid!;
}

Since you have already checked in your code. You can add the non null assertion operator.

Playground link

  • Related