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.
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.
The code you have provided is correct if your expected behaviour is
errors array.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!;
! 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.null also. ! after variable then your code may show compile time error. But if you add ! then it will compile without error.ErrorResult | undefined otherwise it may raise an exception at run time.Here are some links which will be helpful to understand the concept better.
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);