Home > Mobile >  Nested ternary into an independent statement typescript?
Nested ternary into an independent statement typescript?

Time:01-13

I am getting the above error with the example code below, I am quite new to nested ternary operations so your help would be appreciated. Example code below:

  get notEmptyProduct(): string[] {
    return this.contractSettings.allowedRegularEstimateProducts && this.contractSettings.allowedRegularEstimateProducts.length ? this.contractSettings.allowedRegularEstimateProducts : this.contractSettings.allowedControlEstimateProducts && this.contractSettings.allowedControlEstimateProducts.length ? this.contractSettings.allowedControlEstimateProducts : [];
  }

Extract this nested ternary operation into an independent statement.

CodePudding user response:

Try moving nested ternary to a separate variable.

notEmptyProduct(): string[] { 
const nestedTernaryResult = this.contractSettings.allowedControlEstimateProducts && this.contractSettings.allowedControlEstimateProducts.length ? this.contractSettings.allowedControlEstimateProducts : [];
return this.contractSettings.allowedRegularEstimateProducts &&  this.contractSettings.allowedRegularEstimateProducts.length ?     this.contractSettings.allowedRegularEstimateProducts : nestedTernaryResult;
} 

CodePudding user response:

You can make use of Optional chaining and how javascript process Falsy and Truthy values. The last empty array is to make sure that it returns an empty array in case of other failures to comply with method's return type. This is better than having nested ternary operators I believe.

  get notEmptyProduct(): string[] {
    return (this.contractSettings.allowedRegularEstimateProducts?.length  && this.contractSettings.allowedRegularEstimateProducts) || (this.contractSettings.allowedControlEstimateProducts?.length && this.contractSettings.allowedControlEstimateProducts) || [];
  }
  •  Tags:  
  • Related