简体   繁体   English

如何优化 Typescript 中的 if 语句

[英]How to optimize if statement in Typescript

After declaring two variables param01 and param02 I go ahead and check if the incoming event.pathParameters is not undefined :在声明两个变量param01param02之后,我提前 go 并检查传入的event.pathParameters是否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.虽然它工作正常,但它需要 10 行代码。 I wonder if there is a shorter and more elegant way of getting it done in Typescript我想知道在 Typescript 中是否有更短更优雅的方法来完成它

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

You can use the ?你可以使用? operator 操作员

let param01 = event.pathParameters?.param01 || null;
let param02 = event.pathParameters?.param02 || null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM