简体   繁体   中英

typescript optional parameter check before using

Does tsc give error for code like this with some tscconfig rules?

function buildName(firstName: string, lastName?: string) {
  return firstName + " " + lastName;
}

I think if there is no code to check lastName is not undefined, there must be tsc compiling error. How can I get tsc to give error on compililation.

Concatenating with a variable that contains undefined is weird, but not forbidden by JS, so it won't throw a TS error.

But usually it's not what you want, and indicates a problem. Therestrict-plus-operands TSLint or ESLint rule forbids this:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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