Search code examples
typescriptoptional-parameterstsc

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.


Solution

  • 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. The restrict-plus-operands TSLint or ESLint rule forbids this:

    enter image description here