The ? operator indicate that the property can be nullable / optional. It just means that the compilator will not throw an error if you do not implement this property in your implementation.
You can use ?? operator!
const test: string = null;
console.log(test ?? 'none');
This will print 'none' because test is null. If there is a value for test, it will print that. You can try that here playground typescript
You have several options:
An
ifstatementif (ve.select) { price += ve.price; }Or if you prefer it on one line:
if (ve.select) price += ve.price;The conditional operator version you've shown:
price = ve.select ? price + ve.price : price;...but note that it does an unnecessary assignment when
ve.selectis falsy (though aspriceis presumably a simple variable that's not an issue; with an object property that might be an accessor property it can matter).Using the
&&(logical AND) operator:ve.select && price += ve.price;But note that this is really just an
ifstatement in disguise.Tamรกs Sallai's answer providing an alternative use of the conditional operator (
price += ve.select ? ve.price : 0;).
I'd reverse the ternary and use +=:
price += ve.select ? ve.price : 0;