Skip to content Skip to sidebar Skip to footer

Angular Typeerror: Cannot Read Property of Undefined

Every bit a JavaScript developer, I'chiliad sure yous've encountered the frustrating runtime TypeError Cannot read properties of undefined .TypeScript gives you ii ways of interpreting null  and undefined types, also known equally Type Check Modes, and one of them can avoid this hands disregarded TypeError.

Until TypeScript 2.0, there was merely i blazon check way - regular - and it considers nothing  and undefined every bit subtypes of all other types. This means null and undefined values are valid values for all types.

TypeScript two.0 introduced Strict Type Cheque Mode (also referred to as strict null checking mode). Strict Type Cheque differs from Regular Type Check considering information technology considers null  and undefined types of their own.

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

When undefined becomes a problem

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

              function translatePowerLevel(powerLevel: number): cord {                
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'s over 9000!';
}
}

Nevertheless, this code doesn't handle 0, a valid input - yep, looking at yous, Yamcha.

yamcha

Yamcha's Power Level

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

The translatePowerLevelfunction return value is typed explicitly as cord , but information technology is possibly also returning undefined  when the argument powerLevel  has the value0. Why is TypeScript not triggering an mistake?

In Regular Type Check Mode, TypeScript is aware that a part might return undefined . Simply at the aforementioned fourth dimension, TypeScript infers the return type to be only of type string because TypeScript is widening the undefined type to string type.

As another example, if you assign cypher or undefined to variables while in Regular Blazon Check Mode, TypeScript will infer these variables to be of type any .

              const coffee = null;                
const tea = undefined;

Interpreting undefined or cipher as subtypes of all other types tin pb to runtime problems. For example, if you try to get the length of the result of translateNumber(0) , which is undefined , JavaScript will throw this TypeError at runtime: Cannot read backdrop of undefined (reading 'length').

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

Unfortunately, TypeScript's Regular Type Check Mode is non able to alert you to when you may have made that fault.

Strict Type Check Mode to the Rescue

Strict Type Check Way changes how TypeScript interprets undefined and zilch values. But kickoff, let's enable Strict Type Cheque Mode.

How to Enable Strict Type Check Manner in TypeScript

In the root of your project, at that place should exist a tsconfig.json file. This is the TypeScript's configuration file and you tin can read more about it here.

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

Inside compilerOptions belongings, all we need to practise is add the belongings "strictNullChecks": true .

It will look something like this:

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

At present that we have switched to Strict Type Check Mode, TypeScript throws this error for translatePowerLevel office: Function lacks ending return statement and return type does not include 'undefined' .

That error message is telling you the function is returning undefined implicitly, only its return type does not include undefined in it.

Awesome! TypeScript is now enlightened the return type does not friction match all possible return values, and this could lead to bug at runtime! Only how can you match the return type to all possible return values?

Y'all can either add a return statement and so the part always returns a string (solution #one), or change the return type from cord to cord | undefined (solution #2).

Match All Possible Return Values: Solution #1

Adding a return statement so information technology is always explicitly returning a value - in the lawmaking below, it is at present returning the string zilch .

              // Solution #ane: add a render statement then it always returns a string                
part translatePowerLevel(powerLevel: number): string {
if (powerLevel === 1) {
return 'i';
}
if (powerLevel === two) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'southward over 9000!';
}
// new return statement
return 'zero';
}

Match All Possible Return Values: Solution #ii

Make the undefined return blazon explicit so wherever translatePowerLevel is used, you have to handle nullish values equally well.

              // Solution #two: return type as string | undefined                
part translatePowerLevel(powerLevel: number): cord | undefined {
if (powerLevel === ane) {
return 'one';
}
if (powerLevel === 2) {
return '2';
}
if (powerLevel > ii && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'s over 9000!';
}
}

If you were to compile the post-obit code once more using Solution #two, TypeScript would throw the mistake Object is possibly 'undefined' .

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

When you lot choose a solution like Solution #two, TypeScript expects you to write code that handles possible nullish values.

There'southward no reason not to use Strict Blazon Check Fashion

Now you sympathise how TypeScript interprets goose egg and undefined types and how y'all tin drift your project to Strict Mode.

If you are starting a new project, you should definitely enable Strict Blazon Bank check Mode from the commencement. And in case y'all will migrate from Regular to Strict Type Cheque, our team can help with strategies to practice so in a less painful way.

At Bitovi we highly recommend using - or migrating to - Strict Type Check Mode for Angular application development, as it can help you lot produce better, more reliable code. If you lot need help with building astonishing web apps feel free to reach us at bitovi.com .

martinezwerseree.blogspot.com

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

Postar um comentário for "Angular Typeerror: Cannot Read Property of Undefined"