Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a null in Typescript? [duplicate]

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.


1 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!;  
like image 172
Karthick Vinod Avatar answered Sep 22 '25 19:09

Karthick Vinod