Typescript with --strictNullCheck - check for invalid in a separate method

I like the compiler - strictNullCheck

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. It's great

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

enter image description here

But I am not getting this error:

enter image description here

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

+3


source to share


3 answers


Use a guard type. Type protection is some expression that performs run-time checking that guarantees a type in some scope.

In your case, something like this might work (it's hard to tell since you've inserted images instead of code):



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

      

You can read more about types of guards in the typescript reference at https://www.typescriptlang.org/docs/handbook/advanced-types.html

+2


source


The TypeScript compiler is not that smart. Using:



if (error.headers) {
    return error.headers.get("content-type") || defaultContentType;
} 
return defaultContentType;

      

0


source


It should be pretty simple:

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

      

You can put this in your code as well hasHeaders

, however the typescript compiler may or may not throw this warning.

More details about checking for zeros:

Checking values ​​through their "right" value

You can simply check if this value is "true", ie. this does not null

, undefined

, 0

, false

or ''

, using the value of a logical, ie, if (value) { /* do something */ }

or return value || defaultValue

or return value ? value : defaultValue

etc.

This way you can do something like this:

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

      

It can be a little messy though if the variable names are long.

Using identifiers vs equality checks

Some people prefer to use ===

(and !==

) (identity) instead of ==

(and !=

) (equality) because it ===

is a stricter check; however null == undefined

equals true, whereas null === undefined

equals false, so use the correct one in the correct place!

0


source







All Articles