Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

50
Vistas
Nested ternary into an independent statement typescript?

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.

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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) || [];
  }
7 months ago · Juan Pablo Isaza Denunciar

0

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos