How to return a null in Typescript?

Viewed 231

I would like to know whether this section of code is correct or there is a different way of defining it.

Instead of using error!, is there any way. I would like to know what error! actually means as unable to understand.

2 Answers

The code you have provided is correct if your expected behaviour is

  1. To return the first error from errors array.
  2. You are sure that errors array contains at least one error as you are returning an ErrorResult rather than ErrorResult | undefined or it's other equivalent.

You can re-write it as

// Typescripts infers the type of var to be `ErrorResult | undefined`
let error = errors.find(element => element.error);

// ! tells the compiler that you know error is not `undefined`
return error!;  
  • Then ! mark after variable is known as bang operator or non-null assertion operator. In your case you are returning ErrorResult from your function I guess. Which should not be null.
  • But you have some specific requirement and you want to return null also.
  • If you don't write ! after variable then your code may show compile time error. But if you add ! then it will compile without error.
  • But here you need to make sure that whenever you are working with returned value, you should define it as ErrorResult | undefined otherwise it may raise an exception at run time.

Here are some links which will be helpful to understand the concept better.

  1. In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
  2. Cleaner TypeScript With the Non-Null Assertion Operator

class ErrorResult {
  error: boolean
  constructor(error: boolean) {
    this.error = error;
  }
}

function getError(errors: ErrorResult[]) {
  let error: ErrorResult;
  errors.forEach(element => {
    if (element.error === true) {
      error = element;
    }
  });
  return error!;
}

let myError: ErrorResult | undefined;
myError = getError([new ErrorResult(false)]);
console.log(myError);

let myError2: ErrorResult | undefined;
myError2 = getError([new ErrorResult(true)]);
console.log(myError2);

Related