4

I am having fun with the compiler --strictNullCheck option

I have this method:

enter image description here

enter image description here

I need to check if the headers are not null before i can use them. That's great

Now I would like to move the checking operation to the separate method like this:

enter image description here

But not I'm getting this error:

enter image description here

So there is no way to check if some object or the some of its property is not null in the separate method?

Dawid Dyrcz
  • 317
  • 1
  • 3
  • 9

2 Answers2

3

Use a type guard. A type guard is some expression that performs a runtime check that guarantees the type in some scope.

In your case something like this may work (its hard to tell since you pasted images instead of code):

function hasHeaders(error: Response): error is Response & { headers: Headers} {
    return error.headers != null
}

You can learn more about type guards in typescript handbook at https://www.typescriptlang.org/docs/handbook/advanced-types.html

marzelin
  • 7,822
  • 1
  • 18
  • 35
-1

It should be pretty simple:

if(err.headers != null) {
  return error.headers.get('content-type') || defaultContentType;
} else {
  return defaultContentType; // or whatever
}

You could also put that in your hasHeaders code, however, the typescript compiler may or may not still throw that warning.

A couple more details about checking for nulls though:

Checking values via their 'truthy' value

You can just check if the value is "truthy", i.e. it is not null, undefined, 0, false, or '' by using the value as a boolean, i.e. if (value) { /* do something */ } or return value || defaultValue or return value ? value : defaultValue, etc.

In this way you can do something like this:

return error.headers ?
    (error.headers.get('content-type') || defaultContentType) : 
    defaultContentType /* or whatever */;

Though that can be a little messy if your variable names are long.

Using identify vs equality checks

Some people prefer to use === (and !==) (identity) instead of == (and !=) (equality), because === is a stricter check; however, null == undefined is equal to true, whereas null === undefined is equal to false, so use the correct one in the correct place!

Michael Fedora
  • 508
  • 4
  • 10