Angulr Core Cannot Read Property 'handle' of Undefined Http

As a JavaScript developer, I'yard sure you lot've encountered the frustrating runtime TypeError Cannot read properties of undefined .TypeScript gives you two ways of interpreting zilch  and undefined types, as well known as Type Check Modes, and one of them tin avoid this hands overlooked TypeError.

Until TypeScript 2.0, there was only 1 type bank check mode - regular - and it considers zip  and undefined every bit subtypes of all other types. This means goose egg and undefined values are valid values for all types.

TypeScript two.0 introduced Strict Type Bank check Style (too referred to as strict null checking mode). Strict Type Check differs from Regular Blazon Check because it considers zero  and undefined types of their ain.

I'll show you lot how Regular Type Check handles undefined (the same applies to null ) and how Strict Type Bank check prevents you from introducing unwanted behavior in our code, similar that infamous TypeError Cannot read properties of undefined .

When undefined becomes a trouble

The function translatePowerLevel below takes a number as argument and returns strings i , two , many or it's over 9000! .

              part translatePowerLevel(powerLevel: number): string {                
if (powerLevel === 1) {
render 'ane';
}
if (powerLevel === 2) {
return '2';
}
if (powerLevel > two && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'south over 9000!';
}
}

However, this code doesn't handle 0, a valid input - yeah, looking at y'all, Yamcha.

yamcha

Yamcha'southward Power Level

When JavaScript reaches the end of a function that has no explicit return, it returns undefined .

The translatePowerLevelfunction return value is typed explicitly as string , simply it is possibly also returning undefined  when the argument powerLevel  has the value0. Why is TypeScript not triggering an error?

In Regular Type Cheque Mode, TypeScript is aware that a part might return undefined . But at the same fourth dimension, TypeScript infers the return blazon to be simply of type string considering TypeScript is widening the undefined type to string type.

As some other case, if you assign nothing or undefined to variables while in Regular Type Check Mode, TypeScript will infer these variables to exist of type whatsoever .

              const coffee = cypher;                
const tea = undefined;

Interpreting undefined or null equally subtypes of all other types tin can lead to runtime bug. For example, if you lot endeavor to get the length of the event of translateNumber(0) , which is undefined , JavaScript volition throw this TypeError at runtime: Cannot read properties of undefined (reading 'length').

              const powerLevel = translatePowerLevel(0); // undefined                
console.log(powerLevel.length); // Uncaught TypeError: Cannot read properties of undefined (reading 'length')

Unfortunately, TypeScript's Regular Blazon Check Mode is not able to alarm you to when y'all may have made that mistake.

Strict Blazon Bank check Mode to the Rescue

Strict Blazon Cheque Mode changes how TypeScript interprets undefined and null values. Simply first, let'south enable Strict Type Check Manner.

How to Enable Strict Type Check Manner in TypeScript

In the root of your project, in that location should be a tsconfig.json file. This is the TypeScript's configuration file and you tin read more than about information technology here.

              // tsconfig.json example                
{
"compilerOptions": {
"module": "organization",
"noImplicitAny": true,
"removeComments": truthful,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Inside compilerOptions belongings, all nosotros need to do is add together the belongings "strictNullChecks": true .

It volition wait something like this:

              // tsconfig.json                
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": truthful,
"preserveConstEnums": true,
"outFile": "../../congenital/local/tsc.js",
"sourceMap": true,
"strictNullChecks": truthful
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Now that we accept switched to Strict Type Cheque Mode, TypeScript throws this fault for translatePowerLevel function: Function lacks ending return statement and return type does not include 'undefined' .

That fault message is telling you the function is returning undefined implicitly, but its return blazon does not include undefined in it.

Awesome! TypeScript is now aware the render blazon does not friction match all possible return values, and this could pb to bug at runtime! But how can you match the return type to all possible return values?

Yous tin can either add a return statement so the office always returns a cord (solution #1), or change the render type from cord to string | undefined (solution #2).

Match All Possible Return Values: Solution #ane

Calculation a render statement so information technology is always explicitly returning a value - in the code below, it is at present returning the string zero .

              // Solution #ane: add a render statement then it always returns a string                
function translatePowerLevel(powerLevel: number): string {
if (powerLevel === one) {
return 'ane';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
render 'many';
}
if (powerLevel > 9000) {
return 'information technology\'s over 9000!';
}
// new return statement
render 'cipher';
}

Friction match All Possible Return Values: Solution #2

Make the undefined render type explicit so wherever translatePowerLevel is used, yous accept to handle nullish values every bit well.

              // Solution #ii: return blazon equally cord | undefined                
function translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === 1) {
return '1';
}
if (powerLevel === 2) {
return 'ii';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'s over 9000!';
}
}

If you were to compile the following lawmaking over again using Solution #2, TypeScript would throw the error Object is possibly 'undefined' .

              const powerLevel = translatePowerLevel(0); // undefined                
console.log(powerLevel.length); // Object is possibly 'undefined'.

When you choose a solution similar Solution #2, TypeScript expects you to write lawmaking that handles possible nullish values.

There's no reason not to use Strict Type Check Mode

Now you empathize how TypeScript interprets nada and undefined types and how y'all can migrate your project to Strict Way.

If you are starting a new project, you should definitely enable Strict Type Bank check Mode from the beginning. And in case you will migrate from Regular to Strict Type Bank check, our team can aid with strategies to do and then in a less painful style.

At Bitovi we highly recommend using - or migrating to - Strict Type Cheque Mode for Angular awarding development, as information technology can assistance you lot produce better, more reliable code. If you lot demand help with building amazing web apps feel free to attain usa at bitovi.com .

jonesscrithe.blogspot.com

Source: https://www.bitovi.com/blog/how-to-avoid-the-infamous-cannot-read-properties-of-undefined-with-typescript

0 Response to "Angulr Core Cannot Read Property 'handle' of Undefined Http"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel