How to optimize if statement in Typescript

alphanumeric

After declaring two variables param01 and param02 I go ahead and check if the incoming event.pathParameters is not undefined:

      let param01, param02;

      if (event.pathParameters!=undefined) {
        if (event.pathParameters.param01!=undefined) {
          param01 = event.pathParameters.param01;
        }
        if (event.pathParameters.param02!=undefined) {
          param02 = event.pathParameters.param02;
        }
      }    

While it works fine, it takes 10 lines of code. I wonder if there is a shorter and more elegant way of getting it done in Typescript

Dan Cantir

You can try something like this:

const param01 = event.pathParameters && event.pathParameters.param01 || null;
const param02 = event.pathParameters && event.pathParameters.param02 || null;

or using just one line:

const { param01, param02 } = event.pathParameters || {};

If your environment allows, you can also use Optional chaining.

const param01 = event.pathParameters?.param01; // value or undefined
const param02 = event.pathParameters?.param02; // value or undefined

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

React JavaScript How to optimize this if / or statement

From Dev

how to optimize FirstOrDefault Statement in linq

From Dev

How can i optimize this Update statement?

From Dev

Optimize python if statement

From Dev

Optimize if statement in R

From Dev

Optimize long if statement in Python

From Dev

How optimize module namespace in output typescript of multiple files, use gulp

From Dev

TypeScript: how to optimize compile-bundle-reload cycle?

From Dev

How to build return statement dynamically in typescript?

From Dev

How to convert a TypeScript import statement into a JS Require statement

From Dev

How to convert a TypeScript import statement into a JS Require statement

From Dev

Trying to optimize my if-statement

From Dev

Optimize sql statement with OR in where clause

From Dev

Optimize if-statement to check values

From Java

How to use a typescript enum value in an Angular2 ngSwitch statement

From Dev

MySQL Optimize Nested SELECT and INSERT Statement

From Dev

Please help me optimize this MySQL SELECT statement

From Dev

Optimize Large Switch Statement - AS3

From Dev

Optimize update sql statement with 2 inner selects

From Dev

How to optimize this javascript duplicates

From Dev

How to Optimize the URL in R

From Dev

How to optimize mongoDB query?

From Dev

How to optimize sitecore queries?

From Dev

How to optimize a simple loop?

From Dev

Inefficient UICollectionView ... how to optimize?

From Dev

How to optimize this array loop

From Dev

How to optimize rejection sampling

From Dev

How to Optimize this UDF

From Dev

How to optimize this CUDA kernel